Errorbar plot transparency overlapping - matplotlib

In an errorbar matplotlib plot, the main line, the markers and the errorbars of a same color overlap each other on their countour when I use the alpha parameter. Although my goal was to have a transparency between the two different colors, but not within the same color, as if same color lines, markers and errorbars were only one object. Is that possible?
import matplotlib.pyplot as plt
import numpy as np
Time = np.array([1, 2, 3])
Green = np.array([3, 5, 9])
Blue = np.array([4, 7, 13])
Green_StDev = np.array([0.6, 0.6, 0.7])
Blue_StDev = np.array([0.5, 0.5, 0.6])
plt.errorbar(Time, Green, Green_StDev, marker='o', c='green', alpha=0.5)
plt.errorbar(Time, Blue, Blue_StDev, marker='o', c='blue', alpha=0.5)
plt.show()
Like the example below, but with transparency only between different color objects, differently of the example above.

I think you cannot draw them as one single object since they (marker and error bar) are drawn individually. However, to make it more 'aesthetic', you could redraw a non-transparent marker:
import matplotlib.pyplot as plt
import numpy as np
Time = np.array([1, 2, 3])
Green = np.array([3, 5, 9])
Blue = np.array([4, 7, 13])
Green_StDev = np.array([0.6, 0.6, 0.7])
Blue_StDev = np.array([0.5, 0.5, 0.6])
plt.errorbar(Time, Green, Green_StDev, marker='o', c='green', alpha=0.5)
# Add additional marker
plt.scatter(Time, Green,marker='o', c='green')
plt.errorbar(Time, Blue, Blue_StDev, marker='o', c='blue', alpha=0.5)
# Add additional marker
plt.scatter(Time, Blue, marker='o', c='blue')
plt.show()

Related

Plot circle at the title in matplotlib python

I have a 2 line title and first line has a number at the end of the line.
Can we plot a circle around the number?
Here is the code to generate the figure.
from matplotlib import rcParams
from matplotlib import pyplot as plt
import numpy as np
import os
rcParams.update({'figure.autolayout': True})
some_text = 'XXX'
any_number=15
title = '%s: %d\n YYY ZZZZ WWWWW' % (some_text,any_number)
fig = plt.figure(figsize=(8, 8), dpi=100)
plt.tick_params(axis='y', which='major', labelsize=60, width=3, length=10, pad=40)
plt.tick_params(axis='y', which='minor', labelsize=60, width=3, length=10, pad=40)
ax = plt.gca()
plt.title(title, fontsize=60, pad=40, loc='center', fontweight='semibold')
plt.style.use('ggplot')
ax.set_facecolor('white')
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(True)
for edge_i in ['left']:
ax.spines[edge_i].set_edgecolor("black")
ax.spines[edge_i].set_linewidth(3)
ax.spines[edge_i].set_bounds(0, 1)
x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
plt.yticks(np.arange(0, 1.01, step=0.2))
data_list= np.array([1,1,1,1,1,0.9, 0.8, 0.7, 0.8,0.85])
plt.bar(x, data_list, 0.9, color='indianred',edgecolor="black", linewidth=3,zorder=1)
plt.tick_params(
axis='x', # changes apply to the x-axis
which='both', # both major and minor ticks are affected
bottom=False, # ticks along the bottom edge are off
top=False, # ticks along the top edge are off
labelbottom=False) # labels along the bottom edge are off
figure_name = 'figure_with_circle.png'
figure_file = os.path.join('/Users/burcakotlu/Desktop',figure_name)
fig.savefig(figure_file, dpi=100, bbox_inches="tight")
plt.close(fig)
Here is the current figure and the wanted circle.
One could use the following without ax.bar():
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.set_title('title')
circle1 = plt.Circle((2,4.15), 0.2, color='k', clip_on=False, zorder=100, fill=False)
ax.add_patch(circle1)
ax.set_xlim(0,4)
ax.set_ylim(0,4)
plt.show()
I have found a way to plot circle together with bar plots without distorting bars. Here is the code below:
from matplotlib import rcParams
from matplotlib import pyplot as plt
import numpy as np
import os
import matplotlib.patches as patches
from matplotlib.offsetbox import AnchoredText
rcParams.update({'figure.autolayout': True})
some_text = 'XXX'
any_number=15
title = '%s: %d\n YYY ZZZZ WWWWW' % (some_text,any_number)
fig = plt.figure(figsize=(12,12), dpi=100)
plt.tick_params(axis='y', which='major', labelsize=60, width=3, length=10, pad=40)
plt.tick_params(axis='y', which='minor', labelsize=60, width=3, length=10, pad=40)
ax = plt.gca()
number_of_xxx = '12'
anchored_text_number_of_xxx = AnchoredText(number_of_xxx,
frameon=False, borderpad=0, pad=0.1,
loc='upper right',
bbox_to_anchor=[0.95, 1.3],
bbox_transform=plt.gca().transAxes,
prop={'fontsize': 60,
'fontweight': 'semibold'})
ax.add_artist(anchored_text_number_of_xxx)
circle1 = patches.Circle((0.88, 1.25), radius=0.1, transform=ax.transAxes, zorder=100, fill=False, color='gold', lw=8, clip_on=False)
ax.add_patch(circle1)
ax.set_title(title, fontsize=60, pad=40, loc='center', fontweight='semibold', zorder=50)
ax.set_facecolor('white')
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(True)
for edge_i in ['left']:
ax.spines[edge_i].set_edgecolor("black")
ax.spines[edge_i].set_linewidth(3)
ax.spines[edge_i].set_bounds(0, 1)
x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
ax.set_yticks(np.arange(0, 1.01, step=0.2))
data_list= np.array([1,1,1,1,1,0.9, 0.8, 0.7, 0.8,0.85])
ax.bar(x, data_list, 0.9, color='indianred',edgecolor="black", linewidth=3,zorder=1)
ax.tick_params(
axis='x', # changes apply to the x-axis
which='both', # both major and minor ticks are affected
bottom=False, # ticks along the bottom edge are off
top=False, # ticks along the top edge are off
labelbottom=False) # labels along the bottom edge are off
figure_name = 'figure_with_circle.png'
figure_file = os.path.join('/Users/burcakotlu/Desktop',figure_name)
fig.savefig(figure_file, dpi=100, bbox_inches="tight")
plt.close(fig)

Matpliblib colormap with peak at center and zero at edges

I am looking for a custom colormap that highlights the center (value of 1) and just has white color at the edges (values of 0 and 2). Ideally there should be a gradient from 1 to [0, 2].
Usual colormaps do the opposite: diverges from center (white at center).
Thanks for your help
You can use the from_list method from LinearSegmentedColormap for this from the matplotlib.colors module.
Here, we give 3 colors as a list (["white", "red", "white"]). This can easily be customised by changing any of those color names.
For example:
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
import numpy as np
cmap = LinearSegmentedColormap.from_list('wrw', ["white", "red", "white"], N=256)
a = np.arange(0, 2, 0.01).reshape(20, 10)
fig, ax = plt.subplots()
p = ax.pcolormesh(a, cmap=cmap, vmin=0, vmax=2)
fig.colorbar(p)
plt.show()
You can create based on availbale colormaps from matplotlib.
from matplotlib.colors import ListedColormap
def show_cmap(ax, cmap):
n = 256
ax.imshow(np.tile(np.arange(n), [int(n*0.20),1]),
cmap=cmap,
interpolation="nearest", aspect="auto")
ax.set_xticks([])
ax.set_yticks([])
ax.set_xticklabels([])
ax.set_yticklabels([])
c1 = plt.cm.Blues(range(0, 128))
c2 = c1[::-1]
c = np.vstack([c1, c2])
cmap = ListedColormap(c)
fig, ax = plt.subplots(1, 1, figsize=(7.2, 7.2))
show_cmap(ax, cmap)

matplotlib line plot dont show vertical lines in step function

I do have a plot that only consists of horizontal lines at certain values when I have a signal, otherwise none. So, I am looking for a way to plot this without the vertical lines. there may be gaps between the lines when there is no signal and I dont want the lines to connect nor do I want a line falling off to 0. Is there a way to plot this like that in matplotlib?
self.figure = plt.figure()
self.canvas = FigureCanvas(self.figure)
axes = self.figure.add_subplot(111)
axes.plot(df.index, df["x1"], lw=1.0, c=self.getColour('g', i), ls=ls)
The plot you are looking for is Matplotlib's plt.hlines(y, xmin, xmax).
For example:
import matplotlib.pyplot as plt
y = range(1, 11)
xmin = range(10)
xmax = range(1, 11)
colors=['blue', 'green', 'red', 'yellow', 'orange', 'purple',
'cyan', 'magenta', 'pink', 'black']
fig, ax = plt.subplots(1, 1)
ax.hlines(y, xmin, xmax, colors=colors)
plt.show()
Yields a plot like this:
See the Matplotlib documentation for more details.

How to plot multiple colour on ylable using matplotlib?

I have list of data want to plot on a subplot. Then I want to lable ylable with different set of colour. See the simple code example below:-
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('yellow red blue')
plt.show()
This produces the following image:-
In the resultant image ylable is named as 'yellow red blue' and all in black colour. But I would like to have this label coloured like this:-
'yellow' with yellow colour,
'red' with red colour
and 'blue' with blue colour.
Is it possible with matplotlib?
No. You can't do this with a single text object. You could manually add three different labels, i.e.:
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4])
ax = plt.gca()
ax.text(-0.1, 0.4, 'yellow', color='yellow', rotation=90, transform=ax.transAxes)
ax.text(-0.1, 0.5, 'red', color='red', rotation=90, transform=ax.transAxes)
ax.text(-0.1, 0.6, 'blue', color='blue', rotation=90, transform=ax.transAxes)
plt.show()

Get desired wspace and subplots appropriately sized?

I'm trying to make a plot with one panel up top (colspan = 2) and two plots below, with a controlled amount of space between them. I'd like the bounds of the plots to be in alignment. Here's what I'm starting with:
import cartopy
from matplotlib import pyplot
from matplotlib.gridspec import GridSpec
gs = GridSpec(2, 2, height_ratios=[2, 1], hspace=0, wspace=0)
ax0 = pyplot.subplot(gs[0, :], projection=cartopy.crs.LambertConformal())
ax0.add_feature(cartopy.feature.COASTLINE)
ax0.set_extent([-120, -75, 20, 52], cartopy.crs.Geodetic())
ax1 = pyplot.subplot(gs[1, 0], projection=cartopy.crs.LambertConformal())
ax1.add_feature(cartopy.feature.COASTLINE)
ax1.set_extent([-90, -75, 20, 30], cartopy.crs.Geodetic())
ax2 = pyplot.subplot(gs[1, 1], projection=cartopy.crs.LambertConformal())
ax2.add_feature(cartopy.feature.COASTLINE)
ax2.set_extent([-90, -75, 20, 30], cartopy.crs.Geodetic())
pyplot.show()
First problem is that the wspace=0 parameter doesn't take.
Second problem is (at least this is my guess on how to proceed) calculating a height ratio that will make the width of the upper subplot equal the combined width of the lower subplots (plus any wspace).