I am trying to have two sub-plots in the figure in the Python Script. But I am not able to set the axis separately according to my inputs. Can anybody help me to set the x-axis, y-axis for each of the sub-plot separately?
I am including the piece of code that I have done, which was not giving me the result.
fig = plt.figure()
ax = plt.subplot(121) # To show the ascending order
plt.xlabel ('RF Input Power (dBm)', fontsize = 'small')
plt.ylabel ('Gain (dB)', fontsize = 'small')
tx = plt.title('Gain Vs Ascending RFInputAmpl for ' + str(measuredFrequencyUnderTest) + 'MHz', fontsize = 'small')
axPlotAxis = plt.axis([rfInputMin, rfInputMax, -20.0, 30.0])
# Now, Plot all the gain stages across the RFInput
ax.plot(rfInput_Plot, lna_Pre_Plot, color = 'r', marker = '+', label = 'lna_Pre')
ax.plot(rfInput_Plot, lna_Post_Plot, color = 'm', marker = 'x', label = 'lna_Post')
ax.plot(rfInput_Plot, sampler1_Plot, color = 'k', marker = '*', label = 'Sampler1')
ax.plot(rfInput_Plot, sampler2_Plot, color = 'c', marker = 's', label = 'Sampler2')
ax.plot(rfInput_Plot, vga_Plot, color = 'b', marker = 'p', label = 'VGA')
ax.plot(rfInput_Plot, dagc1_Plot, color = 'g', marker = 'H', label = 'DAGC1')
ax.plot(rfInput_Plot, dagc2_Plot, color = 'y', marker = 'v', label = 'DAGC2')
# Put the Legend
ax.legend(loc='upper center', bbox_to_anchor = (1.3, -0.05), shadow=True,numpoints = 1, prop = legend_font_props, ncol = 3)
# Now, come to the second plot
ay = plt.subplot(122) # To show the descending order
plt.xlabel ('RF Input Power (dBm)', fontsize = 'small')
plt.ylabel ('Gain (dB)', fontsize = 'small', horizontalalignment = 'left')
ty = plt.title('Gain Vs Descending RF Input for '+ str(measuredFrequencyUnderTest)+ 'MHz', fontsize = 'small')
# Now, fix the x axis here in descending order
plt.axis([rfInputMax, rfInputMin, y_Min_Value, y_Max_Value])
plt.minorticks_on()
Is there something wrong that I am performing? Pls help me to correct it.
You can set independent scales very easily (from an ipython -pylab session):
In [8]: ax = plt.subplot(121)
In [9]: ay = plt.subplot(122)
In [10]: ax.set_xlim((-1,2))
In [11]: ax.set_ylim((10,20))
In [12]: ay.set_xlim((-10,4))
In [13]: ay.set_ylim((3,5))
Related
Still new to python so I am still trying to learn and become better. The initial problem was that the y-labels for my gridspec did not stay within the figure size, so I tried to call the tight_layout which solved the initial problem but created another
The problem seems to be that my 1. gridspec which initially have a shared x-axis and stays in 1 "figure" separates into 2 figures when I call the tight_layout command. Can I still have tigh_layout or do I need to have another code for my y-labels to stay within figure size?
To produce the following figure I use the code:
colors = ["tab:blue", "#ed7d74", "#71bf82", "#000000", "C4", "C5", "C6"]
fig = plt.figure(figsize = (13,7))
#gs = fig.add_gridspec(2, hspace=0, height_ratios=[2,1])
gs1 = fig.add_gridspec(2, hspace=0, left=0.05, right=0.6, height_ratios=[2,1])
axs1 = gs1.subplots(sharex=True, sharey=False)
#fig.suptitle(lgn[idx])
mark_size = 3
axs1[0].plot(t, U, '.', markersize = mark_size, color = colors[1], alpha = 1)
axs1[0].plot(t0, U0, '.', markersize = mark_size, color = colors[0], alpha = 1)
axs1[0].plot(t1, U1, '.', markersize = mark_size, color = colors[0], alpha = 1)
axs1[0].plot(t2, U2, '.', markersize = mark_size, color = colors[0], alpha = 1)
axs1[0].plot(t3, U3, '.', markersize = mark_size, color = colors[0], alpha = 1)
axs1[0].plot(t4, U4, '.', markersize = mark_size, color = colors[0], alpha = 1)
axs1[0].set(ylabel="Potential [V]")
axs1[0].grid(alpha = 0.3)
axs1[0].set_ylim(min(U)-0.1, max(U)+0.1)
axs1[1].plot(t, j, '-', markersize = 2, color = colors[2], alpha = 1)
axs1[1].grid(alpha = 0.3)
axs1[1].set(ylabel="j [mA cm$^{-2}$]")
axs1[1].set(xlabel="Time [hours]")
axs1[1].set_ylim(0, max(j)+50)
gs2 = fig.add_gridspec(2, hspace=0.03, left=0.65, right=0.98, top=0.98, bottom=0.02, height_ratios=[2,1])
axs2 = gs2.subplots(sharex=True, sharey=False)
axs2[0].plot(t[IDX4_s-(4*35):IDX4_e+(12*35)+15], U[IDX4_s-(4*35):IDX4_e+(12*35)+15], '.', markersize = mark_size, color = colors[1], alpha = 0.6)
axs2[0].plot(t4, U4, '.', markersize = mark_size, color = colors[0], alpha = 0.6)
#axs2[0].set(ylabel="Potential [V]")
axs2[0].grid(alpha = 0.3)
axs2[0].set_xlim(t[IDX4_s-(4*35)], t[IDX4_e+(12*36)+10])
axs2[1].plot(t[IDX4_s-(4*35):IDX4_e+(12*35)+15], j[IDX4_s-(4*35):IDX4_e+(12*35)+15], '-', markersize = 2, color = colors[2], alpha = 0.6)
axs2[1].grid(alpha = 0.3)
#axs2[1].set(ylabel="j [mA cm$^{-2}$]")
axs2[1].set(xlabel="Time [hours]")
axs2[0].set_yticklabels([])
axs2[1].set_yticklabels([])
axs1[0].fill_between((t[IDX4_s-(4*35):IDX4_e+(12*35)+15]), axs2[0].get_ylim()[0], axs2[0].get_ylim()[1], facecolor=(0,0,0,0.1), edgecolor=(0,0,0,1), zorder = 20)
axs1[1].fill_between((t[IDX4_s-(4*35):IDX4_e+(12*35)+10]), axs2[1].get_ylim()[0]+10, axs2[1].get_ylim()[1], facecolor=(0,0,0,0.1), edgecolor=(0,0,0,1), zorder = 20)# facecolor=colors[3], alpha=0.1)
con1 = ConnectionPatch(xyA=(t[IDX4_s-(4*35)], axs2[0].get_ylim()[0]), coordsA=axs1[0].transData, xyB=(t[IDX4_s-(4*35)], axs2[0].get_ylim()[0]), coordsB=axs2[0].transData, color = colors[3])
fig.add_artist(con1)
con2 = ConnectionPatch(xyA=(t[IDX4_s-(4*35)], axs2[0].get_ylim()[1]), coordsA=axs1[0].transData, xyB=(t[IDX4_s-(4*35)], axs2[0].get_ylim()[1]), coordsB=axs2[0].transData, color = colors[3])
fig.add_artist(con2)
con3 = ConnectionPatch(xyA=(t[IDX4_s-(4*35)], axs2[1].get_ylim()[0]+10), coordsA=axs1[1].transData, xyB=(t[IDX4_s-(4*35)], axs2[1].get_ylim()[0]), coordsB=axs2[1].transData, color = colors[3])#, linestyle='--')
fig.add_artist(con3)
con4 = ConnectionPatch(xyA=(t[IDX4_s-(4*35)], axs2[1].get_ylim()[1]), coordsA=axs1[1].transData, xyB=(t[IDX4_s-(4*35)], axs2[1].get_ylim()[1]), coordsB=axs2[1].transData, color = colors[3])
fig.add_artist(con4)
When I add this code I get the following figure
gs1.tight_layout(fig, rect=[0, 0, 0.6, 1.0])
gs2.tight_layout(fig, rect=[0.65, 0.02, 0.98, 0.98])
As you can see the figure on left splits into 2 figures - can this be solved ?
Instead of using tight_layout() in this specific case, why don't you use subplots_adjust() to change the margins?
E.g. run
plt.subplots_adjust(left=.2, bottom=.2, right=.8, top=.8)
which will give you a lot of space around your panels, and then decrease / increase the values until it looks good.
results = df.groupby('depart')['Survey'].mean().to_frame(name = 'Mean').reset_index()
results.plot(x = 'Unit', y = 'Mean', marker = 'o', figsize=(8,5))
plt.grid(True)
plt.ylim(3.60, 5.00)
plt.show()
how do I add the value labels on top of the markers?
thanks!
One way is using annotate
results.plot(x = 'Unit', y = 'Mean', marker = 'o', figsize=(8,5))
plt.grid(True)
plt.ylim(3.60, 5.00)
ax = plt.gca()
for i, val in enumerate(results['Mean']):
label = results.loc[i, 'Mean']
ax.annotate(label, (i, val), ha='center')
plt.show()
I need to plot data sites on a map. For example, survey "DEPROAS" has five stations so, I need to plot'em and insert it in legend guide. But, when I do this, instead of plotting just once (representative of these five stations), It plots five dots. Any idea? Figure and code below.
#### DEPROAS #### - Cabo Frio
fcf1=[-22-(59.030/60),-42-(07.340/60)]
fcf2=[-23-(05.444/60),-41-(54.700/60)]
fcf=[fcf1,fcf2]
fcf=np.array(fcf)
lat_fcf = fcf[0:len(fcf),0]
lon_fcf = fcf[0:len(fcf),1]
x_fcf,y_fcf=m(lon_fcf,lat_fcf)
plt.plot(x_fcf[0],y_fcf[0], 'o', label='DEPROAS', color='#88ff4d', zorder = 3000)
plt.plot(x_fcf[1],y_fcf[1], 'o', label='DEPROAS', color='#88ff4d', zorder = 3000)
#### DEPROAS #### - Ubatuba
fub1=[-23-(43.560/60),-44-(53.860/60)]
fub2=[-24-(04.028/60),-44-(39.005/60)] ##rever nos dados no lab
fub=[fub1,fub2]
fub=np.array(fub)
lat_fub = fub[0:len(fub),0]
lon_fub = fub[0:len(fub),1]
x_fub,y_fub=m(lon_fub,lat_fub)
plt.plot(x_fub[0],y_fub[0], 'o', label = 'DEPROAS', color='#88ff4d', zorder = 3000)
plt.plot(x_fub[1],y_fub[1], 'o', label = 'DEPROAS', color='#88ff4d', zorder = 3000)
#### DEPROAS #### - Guanabara
fbg1=[-23-(18.34/60),-42-(45.81/60)]
fbg=[fbg1]
fbg=np.array(fbg)
lat_fbg = fbg[0:len(fbg),0]
lon_fbg = fbg[0:len(fbg),1]
x_fbg,y_fbg=m(lon_fbg,lat_fbg)
plt.plot(x_fbg[0],y_fbg[0], 'o', label = 'DEPROAS', color='#88ff4d', zorder = 3000)
You plot 5 series with label "DEPROAS" therefore your legend has 5 entries of all these markers and labels.
According to legend guide you have to construct custom legend and put all desired series to a list and plot it in a legend:
...
series1, = plt.plot(x_fub[0],y_fub[0], 'o', label = 'DEPROAS', color='#88ff4d', zorder = 3000)
plt.plot(x_fub[1],y_fub[1], 'o', label = 'DEPROAS', color='#88ff4d', zorder = 3000)
# make custom legend for series1
plt.legend(handles=[series1], loc=2)
...
I have a 4x3 grid. I have 1 broken horizontal bar plot in the first row followed by 9 scatter plots. The height of the bar plot needs to be 2x height of the scatter plots. I am using gridspec to achieve this. However, it doesn't plot the bar plot completely. See picture below:
The complete bar plot looks like this
I am not sure why is this happening. Any suggestions?
Here's my code:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import gridspec
#####Importing Data from csv file#####
dataset1 = np.genfromtxt('dataSet1.csv', dtype = float, delimiter = ',', skip_header = 1, names = ['a', 'b', 'c', 'x0'])
dataset2 = np.genfromtxt('dataSet2.csv', dtype = float, delimiter = ',', skip_header = 1, names = ['a', 'b', 'c', 'x0'])
dataset3 = np.genfromtxt('dataSet3.csv', dtype = float, delimiter = ',', skip_header = 1, names = ['a', 'b', 'c', 'x0'])
corr1 = np.corrcoef(dataset1['a'],dataset1['x0'])
corr2 = np.corrcoef(dataset1['b'],dataset1['x0'])
corr3 = np.corrcoef(dataset1['c'],dataset1['x0'])
corr4 = np.corrcoef(dataset2['a'],dataset2['x0'])
corr5 = np.corrcoef(dataset2['b'],dataset2['x0'])
corr6 = np.corrcoef(dataset2['c'],dataset2['x0'])
corr7 = np.corrcoef(dataset3['a'],dataset3['x0'])
corr8 = np.corrcoef(dataset3['b'],dataset3['x0'])
corr9 = np.corrcoef(dataset3['c'],dataset3['x0'])
fig = plt.figure(figsize = (8,8))
gs = gridspec.GridSpec(4, 3, height_ratios=[2,1,1,1])
def tornado1():
np.set_printoptions(precision=4)
variables = ['a1','b1','c1','a2','b2','c2','a3','b3','c3']
base = 0
values = np.array([corr1[0,1],corr2[0,1],corr3[0,1],
corr4[0,1],corr5[0,1],corr6[0,1],
corr7[0,1],corr8[0,1],corr9[0,1]])
variables=zip(*sorted(zip(variables, values),reverse = True, key=lambda x: abs(x[1])))[0]
values = sorted(values,key=abs, reverse=True)
# The y position for each variable
ys = range(len(values))[::-1] # top to bottom
# Plot the bars, one by one
for y, value in zip(ys, values):
high_width = base + value
# Each bar is a "broken" horizontal bar chart
ax1= plt.subplot(gs[1]).broken_barh(
[(base, high_width)],
(y - 0.4, 0.8),
facecolors=['red', 'red'], # Try different colors if you like
edgecolors=['black', 'black'],
linewidth=1,
)
# Draw a vertical line down the middle
plt.axvline(base, color='black')
# Position the x-axis on the top/bottom, hide all the other spines (=axis lines)
axes = plt.gca() # (gca = get current axes)
axes.spines['left'].set_visible(False)
axes.spines['right'].set_visible(False)
axes.spines['top'].set_visible(False)
axes.xaxis.set_ticks_position('bottom')
# Make the y-axis display the variables
plt.yticks(ys, variables)
plt.ylim(-2, len(variables))
plt.draw()
return
def correlation1():
corr1 = np.corrcoef(dataset1['a'],dataset1['x0'])
print corr1[0,1]
corr2 = np.corrcoef(dataset1['b'],dataset1['x0'])
print corr2[0,1]
corr3 = np.corrcoef(dataset1['c'],dataset1['x0'])
print corr3[0,1]
ax2=plt.subplot(gs[3])
ax2.scatter(dataset1['a'],dataset1['x0'],marker = '.')
ax2.set_xlabel('a1')
ax2.set_ylabel('x01')
ax3=plt.subplot(gs[4])
ax3.scatter(dataset1['b'],dataset1['x0'],marker = '.')
ax3.set_xlabel('b1')
#ax3.set_ylabel('x01')
ax4=plt.subplot(gs[5])
ax4.scatter(dataset1['c'],dataset1['x0'],marker = '.')
ax4.set_xlabel('c1')
#ax4.set_ylabel('x01')
ax5=fig.add_subplot(gs[6])
ax5.scatter(dataset2['a'],dataset2['x0'],marker = '.')
ax5.set_xlabel('a2')
ax5.set_ylabel('x02')
ax6=fig.add_subplot(gs[7])
ax6.scatter(dataset2['b'],dataset2['x0'],marker = '.')
ax6.set_xlabel('b2')
#ax6.set_ylabel('x02')
ax7=fig.add_subplot(gs[8])
ax7.scatter(dataset2['c'],dataset2['x0'],marker = '.')
ax7.set_xlabel('c2')
#ax7.set_ylabel('x02')
ax8=plt.subplot(gs[9])
ax8.scatter(dataset3['a'],dataset3['x0'],marker = '.')
ax8.set_xlabel('a3')
ax8.set_ylabel('x03')
ax9=plt.subplot(gs[10])
ax9.scatter(dataset3['b'],dataset3['x0'],marker = '.')
ax9.set_xlabel('b3')
#ax9.set_ylabel('x03')
ax10=plt.subplot(gs[11])
ax10.scatter(dataset3['c'],dataset3['x0'],marker = '.')
ax10.set_xlabel('c3')
#ax10.set_ylabel('x03')
plt.show()
return
tornado1()
correlation1()
plt.tight_layout()
plt.show()
Any help would be highly appreciated :-)
In the block of code:
# Plot the bars, one by one
for y, value in zip(ys, values):
high_width = base + value
# Each bar is a "broken" horizontal bar chart
ax1= plt.subplot(gs[1]).broken_barh(
[(base, high_width)],
(y - 0.4, 0.8),
facecolors=['red', 'red'], # Try different colors if you like
edgecolors=['black', 'black'],
linewidth=1,
)
You're reinitializing gs[1] on each loop so in the end, your plot only contains the last bar. You should try something like this instead:
# Plot the bars, one by one
ax1 = plt.subplot(gs[1])
for y, value in zip(ys, values):
high_width = base + value
# Each bar is a "broken" horizontal bar chart
ax1.broken_barh(
[(base, high_width)],
(y - 0.4, 0.8),
facecolors=['red', 'red'], # Try different colors if you like
edgecolors=['black', 'black'],
linewidth=1,
)
Hope that helps.
Is there a way to set parameters for multiple graphs at once - basically defining a default?
What I have right now:
fig = plt.figure()
ax1 = fig.add_subplot(313)
ax1.scatter(entries,gvalues[0], color='b', marker = '1')
ax1.scatter(entries,gvalues[1], color = 'g', marker = 'v')
xticks([z for z in range(N)], namelist)
ylabel('Label1', ha='center', labelpad=28)
ylim(0,)
ax2 = fig.add_subplot(312, sharex=ax1)
ax2.scatter(entries,gvalues[2], color = 'b', marker = '1')
ax2.scatter(entries,gvalues[3], color= 'g', marker = 'v')
ylabel('Label2', ha='center', labelpad=28)
setp(ax2.get_xticklabels(),visible=False)
ylim(0,)
I am going to have a handful of these graphs, and it would be great if I didn't have to set ha = 'center', labelpad = 28 and ylim(0,) everytime.
Cheers
You can use a dictionary to store your options as below:
font_options = dict(ha='center', labelpad=28)
ax1.set_ylabel('Label1', **font_options)
...
ax2.set_ylabel('Label2', **font_options)
The **font_options argument will unpack each of the key-value pairs in the dictionary and apply them within the ylabel function.
Similarly for the ylim option you can store your limits in a variable such as:
ylimit = 0
ylim(ylimit,)