Error while plotting circles using matplotlib - python

I want to draw a (semi-transparent) circle on top of an array of randomly generated points (between [0,1] ) using python. I want the circle to be centered at (0.5, 0.5)
This is the code that I have written:
import numpy as np
import matplotlib.pyplot as plt
x_gal = np.random.rand(20)
y_gal = np.random.rand(20)
x_rand = np.random.rand(5*20)
y_rand = np.random.rand(5*20)
plt.figure(1)
plt.plot( x_gal, y_gal, ls=' ', marker='o', markersize=5, color='r' )
plt.plot( 0.5, 0.5, ls=' ', marker='o', markersize=5, color='r' )
plt.plot( x_rand, y_rand, ls=' ', marker='o', markersize=5, color='b' )
plt.axis('off')
circle1 = plt.Circle((0.5, 0.5), 0.2, color='r', alpha=0.5)
plt.add_artist(circle1)
plt.tight_layout()
plt.show()
Without the lines in the code which refer to circle1, I get normal output (without the desired circle). But when I include the lines in the code which refer to circle1, I get the following error output.
AttributeError: 'module' object has no attribute 'add_artist'
What am I missing here? Any help will be greatly appreciated.

You need to use add_artist from axes, the following is the quickest way to get the current axes using plt.gcf, get current figure, and get_gca, get current axes, also I recommend plt.axis('equal') to draw a circle vs oval:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
x_gal = np.random.rand(20)
y_gal = np.random.rand(20)
x_rand = np.random.rand(5*20)
y_rand = np.random.rand(5*20)
plt.figure(1)
plt.plot( x_gal, y_gal, ls=' ', marker='o', markersize=5, color='r' )
plt.plot( 0.5, 0.5, ls=' ', marker='o', markersize=5, color='r' )
plt.plot( x_rand, y_rand, ls=' ', marker='o', markersize=5, color='b' )
plt.axis('off')
plt.axis('equal')
circle1 = plt.Circle((0.5, 0.5), 0.2, color='r', alpha=0.5)
plt.gcf().gca().add_artist(circle1)
plt.tight_layout()
plt.show()

You need to plot on axis.
import numpy as np
import matplotlib.pyplot as plt
x_gal = np.random.rand(20)
y_gal = np.random.rand(20)
x_rand = np.random.rand(5*20)
y_rand = np.random.rand(5*20)
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot( x_gal, y_gal, ls=' ', marker='o', markersize=5, color='r' )
ax.plot( 0.5, 0.5, ls=' ', marker='o', markersize=5, color='r' )
ax.plot( x_rand, y_rand, ls=' ', marker='o', markersize=5, color='b' )
ax.axis('off')
circle1 = plt.Circle((0.5, 0.5), 0.2, color='r', alpha=0.5)
ax.add_artist(circle1)
plt.tight_layout()
plt.show()
Output:

Related

How to fill graph in empty window with matplotlib

This code only gives an empty window. I try to plot a graph with two lines. Is there any way to attach the graph to the window? Thanks!
import matplotlib.pyplot as plt
import numpy as np
alpha =np.deg2rad(np.linspace(0,180,1000))
sigma_1=190 #kPa
sigma_3=145 #kPa
sigma_delta=(sigma_1+sigma_3)/2 + ( (sigma_1-sigma_3)/2 ) * np.cos(2*alpha) #kPa
def sigma_alpha(s1,s3,a):
return ( (s1+s3)/2 + ( (s1-s3)/2 ) * np.cos(2*alpha) )
def tau_alpha(s1,s3,a):
return (( (s1-s3)/2 )*np.sin(2*alpha) )
plt.figure(figsize=(18,10))
plt.plot(alpha, sigma_alpha(sigma_1, sigma_3, alpha), label=r'$sigma_{$alpha$}$', linewidth=3, color='green')
plt.plot(alpha, tau_alpha(sigma_1, sigma_3, alpha), label = r'$tau_{$alpha$}$', linewidth=3, color='red')
plt.xlabel('Angle $\alpha$ [u"\N{DEGREE SIGN}"]')
plt.ylabel('Spenning[kPa]')
plt.title('Spenningsvariasjon for plan $alpha$ = 0-180')
plt.legend(loc=5, framealpha=1, prop={'size':18})
plt.grid()
plt.minorticks_on()
plt.grid(b=None, which='both', axis='x', linewidth=0.5, linestyle='-')
plt.grid(b=None, which='both', axis='y', linewidth=0.5, linestyle='-')
plt.show()
You get an empty plot due to an error in your 'plt.xlabel' line. The special sign $ is causing the problem. If you read it as a raw string, it should be fixed:
import matplotlib.pyplot as plt
import numpy as np
alpha =np.deg2rad(np.linspace(0,180,1000))
sigma_1=190 #kPa
sigma_3=145 #kPa
sigma_delta=(sigma_1+sigma_3)/2 + ( (sigma_1-sigma_3)/2 ) * np.cos(2*alpha) #kPa
def sigma_alpha(s1,s3,a):
return ( (s1+s3)/2 + ( (s1-s3)/2 ) * np.cos(2*alpha) )
def tau_alpha(s1,s3,a):
return (( (s1-s3)/2 )*np.sin(2*alpha) )
plt.figure(figsize=(18,10))
plt.plot(alpha, sigma_alpha(sigma_1, sigma_3, alpha), label=r'$sigma_{$alpha$}$', linewidth=3, color='green')
plt.plot(alpha, tau_alpha(sigma_1, sigma_3, alpha), label = r'$tau_{$alpha$}$', linewidth=3, color='red')
plt.xlabel(r'Angle $\alpha$ [\circ]$')
plt.ylabel('Spenning[kPa]')
plt.title('Spenningsvariasjon for plan $alpha$ = 0-180')
plt.legend(loc=5, framealpha=1, prop={'size':18})
plt.grid()
plt.minorticks_on()
plt.grid(b=None, which='both', axis='x', linewidth=0.5, linestyle='-')
plt.grid(b=None, which='both', axis='y', linewidth=0.5, linestyle='-')
plt.show()
Note that I've changed N_DEGREES to \circ to obtain the angle character in your label.

Problem with minor thicks and color bar in matplotlib

This is cod for plotting.
Here I have two problems.
import matplotlib
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#### part where data are loaded and defined######
tab1 = pd.read_table("tab1.txt", delim_whitespace=True)
tab2 = pd.read_table("tab2.txt", delim_whitespace=True)
delen = (tab1['val2'] / tab1['val3']) *10**9
dist = tab1['val1']
size = abs(tab1['val4'])
m_Es_S0s = tab2['m1'][tab2['#type']==1]
r_Es_S0s = tab2['r1'][tab2['#type']==1]
m_dEs_dS0s = tab2['m1'][tab2['#type']==2]
r_dEs_dS0s = tab2['r1'][tab2['#type']==2]
m_dSphs = tab2['m1'][tab2['#type']==3]
r_dSphs = tab2['r1'][tab2['#type']==3]
m_Nuclear_SC = tab2['m1'][tab2['#type']==4]
r_Nuclear_SC = tab2['r1'][tab2['#type']==4]
m_GCs_UCDs_cEs = tab2['m1'][tab2['#type']==5]
r_GCs_UCDs_cEs = tab2['r1'][tab2['#type']==5]
m_YMCs = tab2['m1'][tab2['#type']==7]
r_YMCs = tab2['r1'][tab2['#type']==7]
#####part related to figure #########
fig1 = plt.figure(figsize=(10,8),dpi=100)
ax = plt.subplot()
ax.tick_params(axis='both', which='both', direction="in")
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.xscale('log')
plt.yscale('log')
plt.scatter(delen ,delen/(2*3.141592653*size**2), marker='o', s=80, c=dist, cmap='Greys_r', alpha=0.9, norm=matplotlib.colors.LogNorm(), edgecolors='darkorchid', linewidth=0.5)
a1=plt.scatter(m_Es_S0s ,m_Es_S0s/(2*3.141592653*r_Es_S0s**2), marker='o', facecolors='none', edgecolors='mediumblue', linewidth=0.5, s=20)
a2=plt.scatter(m_dEs_dS0s ,m_dEs_dS0s/(2*3.141592653*r_dEs_dS0s**2), marker='o', facecolors='none', edgecolors='lightgreen', linewidth=0.5, s=20)
#a3=plt.scatter(m_dSphs ,m_dSphs/(2*3.141592653*r_dSphs**2), marker='o', facecolors='none', edgecolors='red', linewidth=0.5, s=20)
a4=plt.scatter(m_Nuclear_SC ,m_Nuclear_SC/(2*3.141592653*r_Nuclear_SC**2), marker='o', facecolors='none', edgecolors='dodgerblue', linewidth=0.8, s=20)
#a5=plt.scatter(m_GCs_UCDs_cEs ,m_GCs_UCDs_cEs/(2*3.141592653*r_GCs_UCDs_cEs**2), marker='o', facecolors='none', edgecolors='dimgrey', linewidth=0.5, s=20)
a6=plt.scatter(m_YMCs ,m_YMCs/(2*3.141592653*r_YMCs**2), marker='o', facecolors='none', edgecolors='olive', linewidth=0.7, s=20)
plt.clim(1.8,6.8)
cb = plt.colorbar(pad=0.004)
cb.set_label(label='dist', size='medium', weight='bold')
cb.ax.tick_params(labelsize='large',direction='in')
plt.ylabel('yaxis', fontsize=18)
plt.xlabel('xaxis', fontsize=18)
plt.show()
Resulting plot looks like this:
But, after uncommenting a3 and a5 (so, including more data points on the plot) I am losing all minor ticks on my plot. Figure looks like this
This is first problem why I am losing minor ticks I would like to keep them. Also I would like to keep all markers .... 10^5,10^6,10^7 ......
Another problem is that color bar does not change color. You can notice that my cmap='Greys_r' and points on the plot are ok, but color bar keeps viridis all the time.
How to change color bar to Greys_r?
Tab1 and Tab2 are here:
https://www.dropbox.com/s/gwj72blzallqjl5/tab1.txt?dl=0
https://www.dropbox.com/s/mj4fr8hetsb45eo/tab2.txt?dl=0
Try this, it seems to work.
import matplotlib
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#### part where data are loaded and defined######
tab1 = pd.read_table("tab1.txt", delim_whitespace=True)
tab2 = pd.read_table("tab2.txt", delim_whitespace=True)
delen = (tab1['val2'] / tab1['val3']) *10**9
dist = tab1['val1']
size = abs(tab1['val4'])
m_Es_S0s = tab2['m1'][tab2['#type']==1]
r_Es_S0s = tab2['r1'][tab2['#type']==1]
m_dEs_dS0s = tab2['m1'][tab2['#type']==2]
r_dEs_dS0s = tab2['r1'][tab2['#type']==2]
m_dSphs = tab2['m1'][tab2['#type']==3]
r_dSphs = tab2['r1'][tab2['#type']==3]
m_Nuclear_SC = tab2['m1'][tab2['#type']==4]
r_Nuclear_SC = tab2['r1'][tab2['#type']==4]
m_GCs_UCDs_cEs = tab2['m1'][tab2['#type']==5]
r_GCs_UCDs_cEs = tab2['r1'][tab2['#type']==5]
m_YMCs = tab2['m1'][tab2['#type']==7]
r_YMCs = tab2['r1'][tab2['#type']==7]
#####part related to figure #########
fig1 = plt.figure(figsize=(10,8),dpi=100)
ax = plt.subplot()
ax.tick_params(axis='both', which='both', direction="in")
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.xscale('log')
plt.yscale('log')
cc = plt.scatter(delen ,delen/(2*3.141592653*size**2), marker='o', s=80, c=dist, cmap='Greys_r', alpha=0.9, norm=matplotlib.colors.LogNorm(), edgecolors='darkorchid', linewidth=0.5)
a1=plt.scatter(m_Es_S0s ,m_Es_S0s/(2*3.141592653*r_Es_S0s**2), marker='o', facecolors='none', edgecolors='mediumblue', linewidth=0.5, s=20)
a2=plt.scatter(m_dEs_dS0s ,m_dEs_dS0s/(2*3.141592653*r_dEs_dS0s**2), marker='o', facecolors='none', edgecolors='lightgreen', linewidth=0.5, s=20)
a3=plt.scatter(m_dSphs ,m_dSphs/(2*3.141592653*r_dSphs**2), marker='o', facecolors='none', edgecolors='red', linewidth=0.5, s=20)
a4=plt.scatter(m_Nuclear_SC ,m_Nuclear_SC/(2*3.141592653*r_Nuclear_SC**2), marker='o', facecolors='none', edgecolors='dodgerblue', linewidth=0.8, s=20)
a5=plt.scatter(m_GCs_UCDs_cEs ,m_GCs_UCDs_cEs/(2*3.141592653*r_GCs_UCDs_cEs**2), marker='o', facecolors='none', edgecolors='dimgrey', linewidth=0.5, s=20)
a6=plt.scatter(m_YMCs ,m_YMCs/(2*3.141592653*r_YMCs**2), marker='o', facecolors='none', edgecolors='olive', linewidth=0.7, s=20)
plt.clim(1.8,6.8)
cb = plt.colorbar(cc,pad=0.004)
cb.set_label(label='dist', size='medium', weight='bold')
#cb.ax.tick_params(labelsize='large',direction='in')
import matplotlib.ticker
## set y ticks
y_major = matplotlib.ticker.LogLocator(base = 10, numticks = 15)
ax.yaxis.set_major_locator(y_major)
y_minor = matplotlib.ticker.LogLocator(base = 10, subs = np.arange(1.0, 10.0) * 0.1, numticks = 20)
ax.yaxis.set_minor_locator(y_minor)
ax.yaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())
x_major = matplotlib.ticker.LogLocator(base = 10, numticks = 15)
ax.xaxis.set_major_locator(x_major)
x_minor = matplotlib.ticker.LogLocator(base = 10, subs = np.arange(1.0, 10.0) * 0.1, numticks = 20)
ax.xaxis.set_minor_locator(x_minor)
ax.xaxis.set_minor_formatter(matplotlib.ticker.NullFormatter())
plt.ylabel('yaxis', fontsize=18)
plt.xlabel('xaxis', fontsize=18)
#plt.savefig("out1.png")
plt.show()
Output fig is here.
enter image description here

Colorbar for inset in python

I am trying to add an additional small colorbar for the inset axis. The current code, without that, is
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
import matplotlib.colors as colors
from mpl_toolkits.axes_grid1.inset_locator import mark_inset
A = np.linspace(1,20,20)
B = A
X,Y = np.meshgrid(A,B)
Z = X**2 + Y**2
fig, ax = plt.subplots()
im = ax.pcolor(X, Y, Z, cmap='hot_r')
ax.set_xlabel('x',fontsize=labelsize)
ax.set_ylabel('y',fontsize=labelsize)
ca = fig.colorbar(im)#, shrink=0.5, aspect=5)
axins = ax.inset_axes([0.1, 0.5, 0.25, 0.25])
axins.pcolor(A[0:4], B[0:4], Z[0:4,0:4], cmap='hot_r')
axins.tick_params(axis='both', which='major', labelsize=11)
for axis in ['top','bottom','left','right']:
axins.spines[axis].set_linewidth(1)
axins.spines[axis].set_color('gray')
mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec='gray', lw=1)
plt.tight_layout()
You could create an additional inset axis for the colorbar. E.g. located just right of the inset. Then create a colorbar proving this axis (cax=...).
Please note that pcolor creates faces (large pixels) between the given x and y positions. So, you need one row and one column more of position then the number of colors. The current version of matplotlib gives a warning in case too many colors (or not enough x and y positions) are given.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import mark_inset
A = np.linspace(1, 20, 20)
B = A
X, Y = np.meshgrid(A, B)
Z = X ** 2 + Y ** 2
fig, ax = plt.subplots()
im = ax.pcolor(X, Y, Z[:-1, :-1], cmap='hot_r')
ax.set_xlabel('x', fontsize=12)
ax.set_ylabel('y', fontsize=12)
ca = fig.colorbar(im) # , shrink=0.5, aspect=5)
axins = ax.inset_axes([0.1, 0.5, 0.25, 0.25])
axins_cbar = ax.inset_axes([0.37, 0.5, 0.02, 0.25])
img_in = axins.pcolor(A[0:5], B[0:5], Z[0:4, 0:4], cmap='hot_r')
axins.tick_params(axis='both', which='major', labelsize=11)
for axis in ['top', 'bottom', 'left', 'right']:
axins.spines[axis].set_linewidth(1)
axins.spines[axis].set_color('gray')
mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec='gray', lw=1)
fig.colorbar(img_in, cax=axins_cbar)
plt.tight_layout()
plt.show()

Errorbar in Legend - Pandas Bar Plot

Is it possible to show the error bars in the legend?
(Like i draw in red)
They do not necessarily have to be the correct length, it is enough for me if they are indicated and recognizable.
My working sample:
import pandas as pd
import matplotlib.pyplot as plt
test = pd.DataFrame(data={'one':2000,'two':300,'three':50,'four':150}, index=['MAX'])
fig, ax = plt.subplots(figsize=(5, 3), dpi=230)
ax.set_ylim(-.12,.03)
# barplot
ax = test.loc[['MAX'],['one']].plot(position=5.5,color=['xkcd:camo green'], xerr=test.loc[['MAX'],['two']].values.T, edgecolor='black',linewidth = 0.3, error_kw=dict(lw=1, capsize=2, capthick=1),ax=ax,kind='barh',width=.025)
ax = test.loc[['MAX'],['one']].plot(position=7,color=['xkcd:moss green'], xerr=test.loc[['MAX'],['three']].values.T, edgecolor='black',linewidth = 0.3, error_kw=dict(lw=1, capsize=2, capthick=1),ax=ax,kind='barh',width=.025)
ax = test.loc[['MAX'],['one']].plot(position=8.5,color=['xkcd:light olive green'],xerr=test.loc[['MAX'],['four']].values.T, edgecolor='black',linewidth = 0.3, error_kw=dict(lw=1, capsize=2, capthick=1),ax=ax,kind='barh',width=.025)
# Legende
h0, l0 = ax.get_legend_handles_labels()
l0 = [r'MAX $1$', r'MAX $2$', r'MAX $3$']
legend = plt.legend(h0, l0, borderpad=0.15,labelspacing=0.1, frameon=True, edgecolor="xkcd:black", ncol=1, loc='upper left',framealpha=1, facecolor='white')
legend.get_frame().set_linewidth(0.3)
cur_axes = plt.gca()
cur_axes.axes.get_yaxis().set_ticklabels([])
cur_axes.axes.get_yaxis().set_ticks([])
plt.show()
I tried a few ways, no one works.
With Patch in legend_elements i get no lines for the errorbars, with the errorbar() function i can draw a figure with errorbars, but it semms not to work in the legend:
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
from matplotlib.lines import Line2D
legend_elements = [
Line2D([1,2], [5,4], color='b', lw=1, label='Line'),
Patch(facecolor='orange', edgecolor='r', label='Color Patch'),
matplotlib.pyplot.errorbar(3, 3, yerr=None, xerr=1, marker='s',mfc='xkcd:camo green', mec='black',
ms=20, mew=2, fmt='-', ecolor="black", elinewidth=2, capsize=3,
barsabove=True, lolims=False, uplims=False, xlolims=False, xuplims=False,
errorevery=2, capthick=None, label="error"),
]
test = pd.DataFrame(data={'one':2000,'two':300,'three':50,'four':150}, index=['MAX'])
fig, ax = plt.subplots(figsize=(5, 3), dpi=230)
ax.set_ylim(-.12,.03)
# barplot
ax = test.loc[['MAX'],['one']].plot(position=5.5,color=['xkcd:camo green'], xerr=test.loc[['MAX'],['two']].values.T, edgecolor='black',linewidth = 0.3, error_kw=dict(lw=1, capsize=2, capthick=1),ax=ax,kind='barh',width=.025)
ax = test.loc[['MAX'],['one']].plot(position=7,color=['xkcd:moss green'], xerr=test.loc[['MAX'],['three']].values.T, edgecolor='black',linewidth = 0.3, error_kw=dict(lw=1, capsize=2, capthick=1),ax=ax,kind='barh',width=.025)
ax = test.loc[['MAX'],['one']].plot(position=8.5,color=['xkcd:light olive green'],xerr=test.loc[['MAX'],['four']].values.T, edgecolor='black',linewidth = 0.3, error_kw=dict(lw=1, capsize=2, capthick=1),ax=ax,kind='barh',width=.025)
# Legende
h0, l0 = ax.get_legend_handles_labels()
l0 = [r'MAX $1$', r'MAX $2$', r'MAX $3$']
legend = plt.legend(h0, l0, borderpad=0.15,labelspacing=0.1, frameon=True, edgecolor="xkcd:black", ncol=1, loc='upper left',framealpha=1, facecolor='white')
legend.get_frame().set_linewidth(0.3)
ax.legend(handles=legend_elements, loc='center')
cur_axes = plt.gca()
cur_axes.axes.get_yaxis().set_ticklabels([])
cur_axes.axes.get_yaxis().set_ticks([])
#plt.show()
Implementation based on the idea of
r-beginners:
import pandas as pd
import matplotlib.pyplot as plt
test = pd.DataFrame(data={'one':2000,'two':300,'three':50,'four':150}, index=['MAX'])
fig, ax = plt.subplots(figsize=(5, 3), dpi=150)
ax.set_ylim(0, 6)
ax.set_xlim(0, 2400)
ax1 = ax.twiny()
ax1.set_xlim(0, 2400)
ax1.set_xticks([])
ax.barh(1, width=test['one'], color=['xkcd:camo green'], edgecolor='black',linewidth = 0.3, label='MAX1')
ax.barh(2, width=test['one'], color=['xkcd:moss green'], edgecolor='black',linewidth = 0.3, label='MAX2')
ax.barh(3, width=test['one'], color=['xkcd:light olive green'], edgecolor='black',linewidth = 0.3, label='MAX3')
ax1.errorbar(test['one'], 1, xerr=test['two'], color='k', ecolor='k', fmt=',', lw=1, capsize=2, capthick=1, label='MAX1')
ax1.errorbar(test['one'], 2, xerr=test['three'], color='k', ecolor='k', fmt=',', lw=1, capsize=2, capthick=1, label='MAX2')
ax1.errorbar(test['one'], 3, xerr=test['four'], color='k', ecolor='k', fmt=',', lw=1, capsize=2, capthick=1, label='MAX3')
handler, label = ax.get_legend_handles_labels()
handler1, label1 = ax1.get_legend_handles_labels()
label1 = ['' for l in label1]
ax.legend(handler, label, loc='upper left', handletextpad=1.5)
ax1.legend(handler1, label1, loc='upper left', handletextpad=1., markerfirst=False, framealpha=0.001)
plt.show()
Changes:
ax1 gets the same limit as ax
all strings from label1 are deleted
in ax1.legend() the order of handler and label is exchanged and with the handlertextpad the error bars are shifted to the right
The method I came up with was to draw 'ax.barh' and 'ax1.errorbar()' and then superimpose the legends of each on top of each other. On one side, I minimized the transparency so that the legend below is visible; the error bar looks different because I made it biaxial.
import pandas as pd
import matplotlib.pyplot as plt
test = pd.DataFrame(data={'one':2000,'two':300,'three':50,'four':150}, index=['MAX'])
fig, ax = plt.subplots(figsize=(5, 3), dpi=230)
ax.set_ylim(0, 15)
ax.set_xlim(0, 2400)
ax1 = ax.twiny()
ax.barh(5.5, width=test['one'], color=['xkcd:camo green'], edgecolor='black',linewidth = 0.3, label='MAX1')
ax.barh(7.0, width=test['one'], color=['xkcd:moss green'], edgecolor='black',linewidth = 0.3, label='MAX2')
ax.barh(8.5, width=test['one'], color=['xkcd:light olive green'], edgecolor='black',linewidth = 0.3, label='MAX3')
ax1.errorbar(test['one'], 5.5, xerr=test['two'], color='k', ecolor='k', capsize=3, fmt='|', label='MAX1')
ax1.errorbar(test['one'], 7.0, xerr=test['three'], color='k', ecolor='k', capsize=3, fmt='|', label='MAX2')
ax1.errorbar(test['one'], 8.5, xerr=test['four'], color='k', ecolor='k', capsize=3, fmt='|', label='MAX3')
handler, label = ax.get_legend_handles_labels()
handler1, label1 = ax1.get_legend_handles_labels()
ax.legend(handler, label, loc='upper left', title='mix legend')
ax1.legend(handler1, label1, loc='upper left', title='mix legend', framealpha=0.001)
plt.show()
You can add lines manually on the chart, adjusting the color, thickness and position you prefer. It is a very manual and laborious solution, but it should work.
# Draw line
import matplotlib.lines as ln
import numpy as np
# new clear axis overlay with 0-1 limits
ax2 = plt.axes([0,0,1,1], facecolor=(1,1,1,0))
x1,y1 = np.array([[0.18, 0.21], [0.831, 0.831]])
line1 = ln.Line2D(x1, y1, lw=1, color='black', alpha=1)
x2,y2 = np.array([[0.18, 0.21], [0.783, 0.783]])
line2 = ln.Line2D(x2, y2, lw=1, color='black', alpha=1)
x3,y3 = np.array([[0.18, 0.21], [0.732, 0.732]])
line3 = ln.Line2D(x3, y3, lw=1, color='black', alpha=1)
ax2.add_line(line1)
ax2.add_line(line2)
ax2.add_line(line3)
plt.show()

python matplotlib plotting many subfigures with the same parameters

My plot is like the following
fig = plt.figure(figsize=(7,3))
ax1 = fig.add_subplot(1,3,1)
ax2 = fig.add_subplot(1,3,2)
ax3 = fig.add_subplot(1,3,3)
ax1.scatter(x11, y11, s=50, alpha=0.5, c='orange', marker='o')
ax1.scatter(x12, y12, s=50, alpha=0.5, c='blue', marker='s')
ax2.scatter(x21, y21, s=50, alpha=0.5, c='orange', marker='o')
ax2.scatter(x22, y22, s=50, alpha=0.5, c='blue', marker='s')
ax3.scatter(x31, y31, s=50, alpha=0.5, c='orange', marker='o')
ax3.scatter(x32, y32, s=50, alpha=0.5, c='blue', marker='s')
It seems kinda redundant to set s=50, alpha=0.5 over and over. Is there a way to set them once for all? Also for color and marker, is there a way to write them in one place so it's easier to modify?
You could do this:
fig = plt.figure(figsize=(7,3))
ax1 = fig.add_subplot(1,3,1)
ax2 = fig.add_subplot(1,3,2)
ax3 = fig.add_subplot(1,3,3)
xs = [x11, x12, x21, x22, x31, x32]
ys = [y11, y12, y21, y22, y31, y32]
cs = ['orange', 'blue']
ms = 'os'
for j in xrange(len(xs)):
ax1.scatter(xs[j], ys[j], s=50, alpha=0.5, c=cs[j % 2], marker=ms[j % 2])
I like organizing the data and styles, and then using that to organize the plotting. Generating some random data to make a runnable example:
import matplotlib.pyplot as plt
from numpy.random import random
fig, axs = plt.subplots(3, figsize=(7,3)) #axs is an array of axes
orange_styles = {'c':"orange", 'marker':'o'}
blue_styles = {'c':"blue", 'marker':'s'}
pts = []
for i in range(12):
pts.append(random(4))
orange_x = pts[0:3] # organized data is lists of lists
orange_y = pts[3:6]
blue_x = pts[6:10]
blue_y = pts[10:12]
for ax, x, y in zip(axs, orange_x, orange_y): #all the orange cases
ax.scatter(x, y, s=50, alpha=0.5, **orange_styles) # **kwds
for ax, x, y in zip(axs, blue_x, blue_y):
ax.scatter(x, y, s=50, alpha=0.5, **blue_styles)

Categories