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.
Related
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
I would like to show the topmost minor gridline (at 2.25) in its full width without adjusting the limits manually. How can I achieve this?
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
fig, ax = plt.subplots(constrained_layout=True)
ax.yaxis.set_tick_params(which='minor', width=5)
ax.plot(t, s)
ax.yaxis.set_major_locator(mpl.ticker.MultipleLocator(0.50))
ax.yaxis.set_minor_locator(mpl.ticker.MultipleLocator(0.25))
ax.grid(linewidth=5, axis='y', which='both')
ax.set_ylim(0, 2.25)
plt.show()
Adjusting edge gridline visibility in matplotlib
There are a couple ways to accomplish what you're looking for. I think the best method would be to hide the top and right spines. Alternatively, ax.grid takes Line2D args which includes clip_on. Setting clip_on=False has the intended effect of making the ax box not clip the line - but it does result in the top spine going through the grid line (which is not very attractive in my opinion). Lastly, as you mention, you could make a minor increase in y lim (to 2.26 or 2.27) and that would also make the top grid line more visible.
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(15,12))
axes = axes.flatten()
ax = axes[0]
ax.yaxis.set_tick_params(which='minor', width=5)
ax.plot(t, s)
ax.yaxis.set_major_locator(mpl.ticker.MultipleLocator(0.50))
ax.yaxis.set_minor_locator(mpl.ticker.MultipleLocator(0.25))
ax.grid(linewidth=5, axis='y', which='both', clip_on=False)
[ax.spines[s].set_visible(False) for s in ['top', 'right']]
ax.set_ylim(0, 2.25)
ax.set_title('Hide top/right spines', fontsize=16, fontweight='bold')
ax = axes[1]
ax.yaxis.set_tick_params(which='minor', width=5)
ax.plot(t, s)
ax.yaxis.set_major_locator(mpl.ticker.MultipleLocator(0.50))
ax.yaxis.set_minor_locator(mpl.ticker.MultipleLocator(0.25))
ax.grid(linewidth=5, axis='y', which='both', zorder=3, clip_on=False)
ax.set_ylim(0, 2.25)
ax.set_title('Make clip_on=False', fontsize=16, fontweight='bold')
ax = axes[2]
ax.yaxis.set_tick_params(which='minor', width=5)
ax.plot(t, s)
ax.yaxis.set_major_locator(mpl.ticker.MultipleLocator(0.50))
ax.yaxis.set_minor_locator(mpl.ticker.MultipleLocator(0.25))
ax.grid(linewidth=5, axis='y', which='both')
ax.set_ylim(0, 2.265)
ax.set_title('Increase ylim to 2.265', fontsize=16, fontweight='bold')
axes[3].axis('off')
I have tried a number of different things to fix my chart, from zorder on the plots to plt.rcParams.
I feel that this is such a simple problem but I just dont know where I have gone wrong. As you can see the bottom annotation in cyan blue is unreadable and mashed with the y label.
Ideally, the annotation sits over the y label to a point where text inside annotation is readable.
If possible just for the annotation to sit on top and still overlay the y label..something like this
Any help on this would be greatly appreciated.
ax = df.plot(x=df.columns[0], y=df.columns[1], legend=False, zorder=0, linewidth=1)
y1 =df.loc[:, df.columns[2]].tail(1)
y2= df.loc[:, df.columns[1]].tail(1)
colors = plt.rcParams["axes.prop_cycle"].by_key()["color"]
print(colors)
for var in (y1, y2):
plt.annotate('%0.2f' % var.max(), xy=(1, var.max()), zorder=1, xytext=(8, 0),
xycoords=('axes fraction', 'data'),
textcoords='offset points',
bbox=dict(boxstyle="round", fc=colors[0], ec=colors[0],))
ax2 = ax.twinx()
df.plot(x=df.columns[0], y=df.columns[2], ax=ax2, legend=False, color='#fa8174', zorder=0,linewidth=1)
ax.figure.legend(prop=subtitle_font)
ax.grid(True, color="white",alpha=0.2)
pack = [df.columns[1], df.columns[2], freq[0]]
plt.text(0.01, 0.95,'{0} v {1} - ({2})'.format(df.columns[1], df.columns[2], freq[0]),
horizontalalignment='left',
verticalalignment='center',
transform = ax.transAxes,
zorder=10,
fontproperties=subtitle_font)
ax.text(0.01,0.02,"Sources: FRED, Quandl, #Paul92s",
color="white",fontsize=10,
horizontalalignment='left',
transform = ax.transAxes,
verticalalignment='center',
zorder=20,
fontproperties=subtitle_font)
ax.xaxis.set_major_locator(matplotlib.dates.YearLocator())
ax.xaxis.set_minor_locator(matplotlib.dates.MonthLocator((4,7,10)))
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%Y"))
ax.xaxis.set_minor_formatter(ticker.NullFormatter()) # matplotlib.dates.DateFormatter("%m")
plt.setp(ax.get_xticklabels(), rotation=0, ha="center", zorder=-1)
plt.setp(ax2.get_yticklabels(), rotation=0, zorder=-1)
plt.setp(ax.get_yticklabels(), rotation=0, zorder=-1)
plt.gcf().set_size_inches(14,7)
ax.set_xlabel('Data as of; {0}'.format(df['Date'].max().strftime("%B %d, %Y")), fontproperties=subtitle_font)
y1 =df.loc[:, df.columns[2]].tail(1)
y2= df.loc[:, df.columns[1]].tail(1)
for var in (y1, y2):
plt.annotate('%0.2f' % var.max(), xy=(1, var.max()), zorder=1,xytext=(8, 0),
xycoords=('axes fraction', 'data'),
textcoords='offset points',
bbox=dict(boxstyle="round", fc="#fa8174", ec="#fa8174"))
plt.title('{0}'.format("FRED Velocity of M2 Money Stock v Trade Weighted U.S. Dollar Index: Broad"),fontproperties=heading_font)
ax.texts.append(ax.texts.pop())
ax.set_facecolor('#181818')
ax.figure.set_facecolor('#181818')
plt.rcParams['axes.axisbelow'] = True
I don't figure out why zorder doesn't work, but you can directly set the label style of tick labels:
import matplotlib.pyplot as plt
import numpy as np
from numpy.random import rand
import matplotlib.patches as mpatches
fig, ax = plt.subplots(1, 1)
ax.plot(rand(100), '^', color='r')
for label in ax.get_xticklabels():
label.set_bbox(dict(facecolor='orange'))
ax1 = ax.twinx()
ax1.plot(rand(100), 'o', color='b')
index_to_add_bbox = [2, 4]
ax1_labels = ax1.get_yticklabels()
for i in index_to_add_bbox:
ax1_labels[i].set_bbox(dict(boxstyle='Circle', facecolor='orange'))
plt.show()
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:
I am trying to make this animated so that the dot and the green line move due to the for loop. This code displays 3 different graphs one below the other. The middle graph has no animation section.
x =lag_range
count = 0
plt.ion()
fig, ax = plt.subplots()
for b in x:
plt.subplot(311)
plt.plot(x,pear_corr, color='b', linewidth=1.5, label ='Pearson')
plt.plot(x,spear_corr, color ='r', linewidth=1.5, label='Spearman')
plt.plot(x[count],pear_corr[count],'yo')
plt.legend()
axes = plt.gca()
plt.ylabel('Correlation coefficients')
plt.xlabel('Lag times /days')
axes.set_xlim([min(lag_list),last])
axes.set_ylim(-1,1)
plt.subplot(312)
plt.plot(x,pear_p_values, color='b', linewidth=1.5)
plt.plot(x,spear_p_values, color ='r', linewidth=1.5)
axes = plt.gca()
plt.ylabel('P values')
plt.xlabel('Lag times /days')
axes.set_xlim([min(lag_list),last])
plt.subplot(313)
ax1 = plt.subplot(313)
x_for_p = range(len(x_prices))
ax1.plot(x_for_p, x_prices, color ='grey', linewidth=1.5)
ax1.set_ylabel('Share price', color ='grey')
ax1.tick_params('y', colors='grey')
ax1.set_xlabel('Days')
axes = plt.gca()
axes.set_xlim([min(lag_list),(2*last)])
ax2 = ax1.twinx()
x_for_den = range(b,(b+len(x_prices)))
ax2.plot(x_for_den, y_planes, color='g', linewidth=1.5)
ax2.set_ylabel('Plane density', color='g')
ax2.tick_params('y', colors='g')
count += 1
plt.pause(2)
plt.draw()
cross_corr2_vis(prices, density_p3)
If you could share a working code or just definitions of variables pear_corr, spear_corr, etc., the following code might have not resulted in this simple animation:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
N_points = 1000
x = np.linspace(0,2.*np.pi,N_points)
y = np.sin(x)
fig, ax = plt.subplots()
ax.set_xlim([0,2.*np.pi])
ax.set_ylim([-1,1])
line, = ax.plot( [],[], lw=2, color='g')
sctr = ax.scatter([],[], s=100, color='r')
def animate(i):
line.set_ydata(y[:i+1]) # update
line.set_xdata(x[:i+1])
sctr.set_offsets((x[i],y[i]))
return line,sctr
ani = animation.FuncAnimation(fig, animate, N_points, interval=5, blit=True)
plt.show()