Plots in a loop in two separate figures - python

I have a loop over every month in the year and I want to produce two plots from it, relating to groups A and B. I'd like all curves for group A for the year on the same plot and all curves for B on a separate one. At the moment I can either put all of A on one plot by not plotting B at all, or make twelve plots with one for A and one for B made by every iteration. So I want this for both A and B:
If I try the below code for A and B, I get every curve on an individual plot. If I comment out the subplots lines they all get put on the same figure, both A and B. I guess there might be some plot() option instead of subplots, but plt.plot() throws an error.
fig1, ax1 = plt.subplots()
short1.cumsum().plot(title='')
text = fig1.text(0.50, 0.02,
'Totals')
fig1.tight_layout(rect=(0,.05,1,1))
plt.legend(loc = 'best')
fig2, ax2 = plt.subplots()
short2.cumsum().plot(title='')
text = fig2.text(0.50, 0.02,
'Totals')
fig2.tight_layout(rect=(0,.05,1,1))
plt.legend(loc = 'best')
This is basic and will be in docs, but I'm not sure what to google to find it. Thanks for any suggestions! :)

Related

Remove plot from matplotlib subplot, but keep legend visible

I have a very customized subplot set up.
fig = plt.figure(figsize=(12, 10))
gs = fig.add_gridspec(nrows=2, ncols=2, width_ratios=[3, 1])
ax = fig.add_subplot(gs[:, 0])
ax3 = fig.add_subplot(gs[-1, -1])
ax4=fig.add_subplot(gs[0, 1])
This sets up 3 slots for plotting: one that takes up half the space on the left, and two smaller ones on the right. However, I only want the bottom right to actually be a plot. I want the top right to be the space where the legend for the larger plot on the left to go. I could just use the axes from ax to do this, but that shifts the whole plotting space off. Instead I thought of trying to just create ax4 and place the ax legend there.
lines = []
labels = []
for ax in fig.get_axes():
ln, la = ax.get_legend_handles_labels()
lines.extend(ln)
labels.extend(la)
legend = ax4.legend(lines, labels, labelspacing=0.1, loc=(-0.3,0.6), fontsize='xx-large')
fig.tight_layout()
This puts the legend exactly where I want it, but the blank figure shows up, which I don't want. Is it possible to accomplish what I want using this method? If not, what is my alternative? Picture below to better understand.
You can use ax4.axis('off') to make axis 4 invisible if you want to stick to your approach.
However, I don't see why you don't just skip creating axis 4 and just use fig.legend() instead of ax.legend(). Then the legend is placed outside the axis and you can then control the exact position just as you already did with the loc keyword.

Adding legend by list within subplot Matplotlib

I want to plot 2 different graphs in one plot. One graph is just one line, so no problem with labeling the legend. In df_2_plot is a list of tickers that is delivered, so more lines and more tickers within legend. If I label them like this, I only receive the list several times in the legend, instead of the right ticker for each line.
I tried to work with for loops but can't find a solution.
def func_plot_DataFrame(df_2_plot, legend_lst):
y1 = df_2_plot
y2 = df_infektionsgeschehen
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(y1, label = legend_lst)
ax2.plot(y2, 'grey', linewidth=2, alpha=0.3, label = 'Neuinfektionen')
plt.show()
You need to use ax1.legend instead of using the label argument directly in ax1.plot
ax1.legend(labels=legend_lst)
Have a look at the official documentation here

python, histogram,data fitting

I wish to make a Histogram in Python 3 from an input file containing the raw data of energy (.dat). And on the same plot I want to plot a formula(distribution analytical, pho vs energy). It is easy to plot them seperately, but I need combined version. Can you help?
If you want 2 plots in the same figure look into this:
https://matplotlib.org/3.1.0/gallery/subplots_axes_and_figures/subplots_demo.html
fig, (ax1, ax2) = plt.subplots(2)
If you want to have 2 plots int he same plot that share axis use this:
https://matplotlib.org/3.1.0/gallery/subplots_axes_and_figures/two_scales.html#sphx-glr-gallery-subplots-axes-and-figures-two-scales-py
ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis

Matplotlib Subplot axes sharing: Apply to every other plot?

I am trying to find a way to apply the shared axes parameters of subplot() to every other plot in a series of subplots.
I've got the following code, which uses data from RPM4, based on rows in fpD
fig, ax = plt.subplots(2*(fpD['name'].count()), sharex=True, figsize=(6,fpD['name'].count()*2),
gridspec_kw={'height_ratios':[5,1]*fpD['name'].count()})
for i, r in fpD.iterrows():
RPM4[RPM4['name'] == RPM3.iloc[i,0]].plot(x='date', y='RPM', ax=ax[(2*i)], legend=False)
RPM4[RPM4['name'] == RPM3.iloc[i,0]].plot(kind='area', color='lightgrey', x='date', y='total', ax=ax[(2*i)+1],
legend=False,)
ax[2*i].set_title('test', fontsize=12)
plt.tight_layout()
Which produces an output that is very close to what I need. It loops through the 'name' column in a table and produces two plots for each, and displays them as subplots:
As you can see, the sharex parameter works fine for me here, since I want all the plots to share the same axis.
However, what I'd really like is for all the even-numbered (bigger) plots to share the same y axis, and for the odd-numbered (small grey) plots to all share a different y axis.
Any help on accomplishing this is much appreciated, thanks!

Matplotlib x-axis overlap

I have two lists, x_axis which is list of time in the format of '12:30:00'. The y-axis is percent values. I need to plot all the values on a graph, however since x-axis string is too long they overlap. Is there anyway I can have matplotlib not show every single time on x-axis? Any help would be appreciated.
You could rotate and print every 2nd ticklabel:
_ = plt.plot(df['str_time'], df.Pct, 'ro')
ax = plt.gca()
plt.axis([0,24,0,50])
plt.xticks(rotation=90)
for label in ax.get_xaxis().get_ticklabels()[::2]:
label.set_visible(False)
Output:
You can rotate your label to show the list time using the below code.
plt.xticks(rotation=90)
One way to do this automatically is by using autofmt_xdate
fig.autofmt_xdate():
for getting fig object you will have to call the subplot functions
fig, ax = plt.subplots()
Works really well
I needed to step x axis digits instead of rotating.
ax.set_xticks(np.arange(0, max_number, 5)) #step 5 digits
Output:

Categories

Resources