I am plotting a graph with 3 y axis, and it shows in the plot window of Spyder instead of saving correctly in a folder. The graph saved in a folder is blank.
Here's my code :
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax3 = ax1.twinx()
plt.figure(figsize = (121, 75))
ax1.set_xlabel('time(s)')
ax1.set_ylabel('y1')
ax2.set_ylabel('y2')
ax3.set_ylabel('y3')
rspine = ax3.spines['right']
rspine.set_position(('axes', 1.15))
plt.xticks(fontsize=50)
plt.yticks(fontsize=50)
ax1.plot(fd[fd.columns[0]], fd[fd.columns[1]], color = 'r', linewidth = 2)
ax2.plot(fd[fd.columns[0]], fd[fd.columns[2]], color = 'g', linewidth = 2)
ax3.plot(fd[fd.columns[0]], fd[fd.columns[3]], color = 'b', linewidth = 2)
ax3.legend([ax1.get_lines()[0], ax2.get_lines()[0], ax3.get_lines()[0]], ['y1', 'y2', 'y3'])
plt.savefig(folder+"/"+str(file_name)+"y1/2/3.png")
plt.close()
Am I doing something wrong here ? I don't call the show() function so I don't understand why the graph shows anyway (when plotting the 3 y axis on the same graph with only using plt.figure(), plt.plot() then plt.save() and close(), it works as intended)
Edit : What I want is to have the graph saved correctly in my folder, with the size I set in plt.figure(), which isn't the case now.
I found what went wrong :
I stead of writing
fig = plt.figure(figsize=(121, 75)) fig, ax1 = plt.subplots(),
I had to write
fig, ax1 = plt.subplots(figsize=(121, 75))
The graph then plots at the size indicated, and doesn't shows in the window of Spyder.
You can use set_size_inches before saving the figure. dpi feature can be use to increase the resolution of the figure also.
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['font.size'] = '50'
fig = plt.figure(figsize=(121, 75), dpi=200)
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax3 = ax1.twinx()
ax1.set_xlabel('time(s)')
ax1.set_ylabel('y1')
ax2.set_ylabel('y2')
ax3.set_ylabel('y3')
rspine = ax3.spines['right']
rspine.set_position(('axes', 1.05))
rspine2 = ax2.spines['right']
rspine2.set_position(('axes', 1.0))
# plt.xticks(fontsize=50)
# plt.yticks(fontsize=50)
ax1.plot(np.arange(100), np.random.rand(100), color='r', linewidth=2)
ax2.plot(np.arange(100), np.random.rand(100), color='g', linewidth=2)
ax3.plot(np.arange(100), np.random.rand(100), color='b', linewidth=2)
ax3.legend([ax1.get_lines()[0], ax2.get_lines()[0], ax3.get_lines()[0]], ['y1', 'y2', 'y3'])
# fig.tight_layout()
figure = plt.gcf()
figure.set_size_inches(121, 75)
plt.savefig("3.png", dpi=None)
plt.close()
Related
I am using secondary y-axis and cmap color but when I plot together the color bar cross to my plot
here is my code
fig,ax1=plt.subplots()
ax1 = df_Combine.plot.scatter('Parameter2', 'NPV (MM €)', marker='s', s=500, ylim=(-10,60), c='Lifetime1 (a)', colormap='jet_r', vmin=0, vmax=25, ax=ax1)
graph.axhline(0, color='k')
plt.xticks(rotation=90)
ax2 = ax1.twinx()
ax2.plot(df_Combine_min_select1["CumEnergy1 (kWH)"])
plt.show()
and here is my plotting
anyone can help how to solve this issue?
Thank you
When you let pandas automatically create a colorbar, you don't have positioning options. Therefore, you can create the colorbar in a separate step and provide the pad= parameter to set a wider gap. Default, pad is 0.05, meaning 5% of the width of the subplot.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
fig, ax1 = plt.subplots()
df_Combine = pd.DataFrame({'Parameter2': np.random.rand(10) * 10,
'NPV (MM €)': np.random.rand(10),
'Lifetime1 (a)': np.random.rand(10) * 25,
})
ax1 = df_Combine.plot.scatter('Parameter2', 'NPV (MM €)', marker='s', s=500, ylim=(-10, 60), c='Lifetime1 (a)',
colormap='jet_r', vmin=0, vmax=25, ax=ax1, colorbar=False)
plt.colorbar(ax1.collections[0], ax=ax1, pad=0.1)
ax2 = ax1.twinx()
ax2.plot(np.random.rand(10))
plt.show()
I have the following code:
fig = plt.figure()
ax1 = plt.subplot(211)
ax2 = plt.subplot(212, sharex = ax1)
ax2 = ax1.twinx()
num = list111.lt(-90).sum(1)
plt.yticks(fontsize = 25)
ax = num.plot(figsize=(45,25), ax=ax2, color = 'Red')
df2.plot(y = 'Close', figsize=(45,25), ax=ax1, color = 'Green')
ax1.grid()
ax.margins(x=0)
I am trying to plot ax1 and ax2 in the same graph. What i am getting is a ghost plot:
How can i get rid of the second ghost plot and move the x axis with label to the top plot?
The statement
ax2 = plt.subplot(212, sharex = ax1)
generates a subplot located beneath the ax1 subplot. But it is in contradiction with the statement
ax2 = ax1.twinx()
which points towards a secondary y-axis on the ax1 axes.
If you want all the data to be plotted only on a single axes, you can delete the first statement and use the .twinx() method:
ax1 = plt.axes()
ax2 = ax1.twinx()
# remaining code
otherwise, use both axes separately with
ax1 = plt.subplot(211)
ax2 = plt.subplot(212, sharex = ax1)
# remaining code
This is my function to create box plot. But it does not show the outliers. any help?
def box_plot_draw (data, box_colors):
#plt.style.use('Solarize_Light2')
fig, ax = plt.subplots()#figsize=(10, 6))
fig.canvas.set_window_title('A Boxplot Example')
fig.subplots_adjust(left=0.075, right=0.95, top=0.9, bottom=0.25) #
bp = ax.boxplot(data, notch=0, sym='+', vert=1, whis=1.5)
plt.setp(bp['boxes'], color='black')
plt.setp(bp['whiskers'], color='black')
plt.setp(bp['fliers'], color='red', marker='+')
box_colors = box_colors
ax.yaxis.grid(True, linestyle='-', which='major', color='lightgrey', alpha=0.5) #what is which?
ax.set_axisbelow(True)
#setting the tile for distribution
ax.set_title('Comparison of the duration of time for two Distributions')
ax.set_xlabel('Distribution')
ax.set_ylabel('Value')
You can test the code using this data.
np.random.seed(10)
collectn_1 = np.random.normal(100, 10, 200)
collectn_2 = np.random.normal(80, 30, 200)
## combine these different collections into a list
data_to_plot = [collectn_1, collectn_2]
box_colors = ['black', 'green']
box_plot_draw (data_to_plot, box_colors)
plt.show()
I am using the Jupyter notebook and I used styles for other functions. But I did not use any style for this function.
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()
I wrote the following code below to do the following graph:
fig, ax = plt.subplots(figsize=(8, 6))
ax.patch.set_facecolor('white')
ax.plot(df.index, df.X1.values, 'b',
label='NMA', linewidth=1.5)
ax.set_ylabel('Index')
ax2 = ax.twinx()
ax2.plot(df.index, df.Y.values, 'r--',
label='Rate', linewidth=1.5)
ax2.set_ylabel('Rate')
lines = ax.get_lines() + ax2.get_lines()
lgd = ax.legend(lines, [line.get_label() for line in lines],
loc='lower center', ncol=2, bbox_to_anchor=(0.5, -0.15),
frameon=False)
ax.set_title('Economic Rate and Index',
weight='bold')
for i in range(5):
plt.axvspan(Dates['Peak'][i], Dates['Trough'][i],
facecolor='grey', alpha=0.5)
plt.grid(False)
plt.savefig('C:\\test.pdf',
bbox_extra_artists=(lgd,), bbox_inches='tight')
I am having a hard time to reproduce this figure in a subplot (2X2). The only thing I would change in each of the subplots is the blue line (X1 in df... for X2, X3...). How can I have a 2X2 subplot of the above graph? Of Course I would only keep one legend at the bottom of the subplots. Thanks for the help.
The data is here and the "Dates" to reproduce the gray bars here.
This is how you could create a 2x2 raster with twinx each:
import matplotlib.pyplot as plt
fig, ((ax1a, ax2a), (ax3a, ax4a)) = plt.subplots(2, 2)
ax1b = ax1a.twinx()
ax2b = ax2a.twinx()
ax3b = ax3a.twinx()
ax4b = ax4a.twinx()
ax1a.set_ylabel('ax1a')
ax2a.set_ylabel('ax2a')
ax3a.set_ylabel('ax3a')
ax4a.set_ylabel('ax4a')
ax1b.set_ylabel('ax1b')
ax2b.set_ylabel('ax2b')
ax3b.set_ylabel('ax3b')
ax4b.set_ylabel('ax4b')
plt.tight_layout()
plt.show()
Result: