Displaying xticks using subplot Python - python

I'm attempting to plot a few subplots. The issue that I'm running into is in labeling the x-axis for each plot since they're all different.
The variables relHazardRate and relHazardFICO are dataframes of size 50 X 2
I attempting to plot the below I'm unable to show the x-axis tick marks (i.e. relHazardRate is a variable ranging from 3% to 6%, and relHazardFICO is a variable ranging from 300-850. Each figure in the subplot will have its own x-axis/ticker (there are 8 such plots) and I have provided my logic for 2 as shown below.
fig, ((ax1, ax2), (ax3, ax4), (ax5, ax6), (ax7, ax8)) = plt.subplots(4, 2,figsize=(12,8))
ax1.plot(relHazardRate['orig_coupon'],relHazardRate['Hazard Multiplier']);
ax1.title.set_text('Original Interest Rate');
ax1.set_xticks(range(len(relHazardRate['orig_coupon'])));
ax1.set_xticklabels(relHazardRate['orig_coupon'].to_list())
ax2.plot(relHazardFICO['orig_FICO'],relHazardFICO['Hazard Multiplier'], 'tab:orange');
ax2.title.set_text('Original FICO');
ax2.set_xticks(range(len(relHazardRate['orig_FICO'])));
ax2.set_xticklabels(relHazardRate['orig_FICO'].to_list())
ax.3 through ax.8 follow a similar decleration as the described above
for ax in fig.get_axes():
ax.label_outer()
The subplot that I get is as follows, I want to label each plot with its own x-axis, as shown this is not happening.

Remove the lines with label_outer.
From the docs:
label_outer()
Only show "outer" labels and tick labels.
x-labels are only kept for subplots on the last row; y-labels only for subplots on the first column
Clearly this is what is causing the behaviour you see in your plot

Related

Plot pandas df into boxplot & histogram

Currently I am trying to plot a boxplot into a histogram (without using seaborn). I have tried many varieties but I always get skewed graphs.
This was my starting point:
#Histogram
df.hist(column="Q7", bins=20, figsize=(14,6))
#Boxplot
df.boxplot(column="Q7",vert=False,figsize=(14,6))
which resulted in the following graph:
As you can see the boxplot and outliers are at the bottom, but I want it to be on top.
Anyone an idea?
You can use subplots and set the percentage of the plot to ensure that the boxplot is first and the hist plot is below. In below example, I am using 30% for boxplot and 70% for bistogram. Also adjusted the spacing between the plots and used a common x-axis using sharex. Hope this is what you are looking for...
fig, ax = plt.subplots(2, figsize=(14, 6), sharex=True, # Common x-axis
gridspec_kw={"height_ratios": (.3, .7)}) # boxplot 30% of the vertical space
#Boxplot
df.boxplot(column="Q7",vert=False,figsize=(14,6), ax=ax[0])
#Histogram
df.hist(column="Q7", bins=20, figsize=(14,6), ax=ax[1])
ax[1].title.set_size(0)
plt.subplots_adjust(hspace=0.1) ##Adjust gap between the two plots

Matplotlib align x-axes on subplots

I am trying to put together a plot that incorporates multiple different data frames that share a common index. Despite setting all the X-axes to the same labels and ticks they still don't lineup within the as be seen with the top x-axis. Causing whitespace on the right y-axis.
Output Graph Here
fig,axe=plt.subplots()
axe.set_xlabel('Total Collectors in Array')
axe.set_ylabel('Energy Generated (MJ)')
plt.xticks(ticks=df.index.values,labels=df.index.values)
axe.plot(df,label= label_list,zorder=0,marker='o')
labelLines(axe.get_lines())
ax3=axe.twiny()
ax2=axe.twinx()
ax3.plot(df3,label=label_list,zorder=1,linewidth=1,linestyle='--')
ax3.axes.xaxis.set_visible(True)
labelLines(ax3.get_lines(),align=False,xvals=[1.5]*10,zorder=2.5)
ax2.set_ylabel('DHW Draw Rate')
ax2.imshow(df2,zorder=2,
cmap='CMRmap',alpha=0.3,origin='lower')
a=ax2.get_xticks().tolist()
label_list1=label_list[:]
ax2.set(xticks=x_lab,xticklabels=x_lab,yticks=y_ticks,yticklabels=label_list1)
fig.tight_layout()
plt.show()

Label Matplotlib subplot y-axes with list of strings

I'm using Matplotlib to create 2 side-by-side horizontal bar charts showing regression coefficient importance across several words. I'd like to label the y-axes with each word in the list.
Every other word is appended to the y-axis when I try this:
# plot word importance bar graphs
fig, axes = plt.subplots(1,2,figsize=(5,10))
plt.subplots_adjust(wspace = 1)
axes[0].set_title('Low revenue')
axes[0].invert_yaxis()
axes[0].barh(np.arange(len(lowrev_topten)), lowrev_topten['Coefficient'])
axes[0].set_yticklabels(list(lowrev_topten['Word']))
axes[0].set_xlabel('Coefficient')
axes[1].set_title('High revenue')
axes[1].invert_yaxis()
axes[1].barh(np.arange(len(highrev_topten)), highrev_topten['Coefficient'])
axes[1].set_yticklabels(list(highrev_topten['Word']))
axes[1].set_xlabel('Coefficient')
However, when I remind it that I'd like to have 10 ticks for 10 words (plt.yticks(np.arange(0,10))), it fixes the second subplot:
# plot word importance bar graphs
fig, axes = plt.subplots(1,2,figsize=(5,10))
plt.subplots_adjust(wspace = 1)
plt.yticks(np.arange(0,10))
axes[0].set_title('Low revenue')
axes[0].invert_yaxis()
axes[0].barh(np.arange(len(lowrev_topten)), lowrev_topten['Coefficient'])
axes[0].set_yticklabels(list(lowrev_topten['Word']))
axes[0].set_xlabel('Coefficient')
axes[1].set_title('High revenue')
axes[1].invert_yaxis()
axes[1].barh(np.arange(len(highrev_topten)), highrev_topten['Coefficient'])
axes[1].set_yticklabels(list(highrev_topten['Word']))
axes[1].set_xlabel('Coefficient')
How do I get both subplots to have the proper y-tick labels?
Seems like you just need to set_yticks for each subplot.
fig, axes = plt.subplots(1,2,figsize=(5,10))
...
axes[0].set_yticks(np.arange(0,10))
axes[1].set_yticks(np.arange(0,10))

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!

Subplot charts plotted within a loop very squashed

I have a dataframe with ~120 features that I would like to examine by year. I am plotting each feature, x = year, y = feature value within a loop. Whilst these plot successfully, the charts are illegible as they are totally squashed.
I have tried using plt.tight_layout() and adjusting the figure size using plt.rcParams['figure.figsize'] but sadly to no avail
for i in range(len(roll_df.columns)):
plt.subplot(len(roll_df.columns), 1, i+1)
name = roll_df.columns[i]
plt.plot(roll_df[name])
plt.title(name, y=0)
plt.yticks([])
plt.xticks([])
plt.tight_layout()
plt.show()
The loop runs but all plots are so squashed on the y-axis as to become illegible:
Matplotlib will not automatically adjust the size of your figure. So if you add more subplots below each other, it will split the available space instead of extending the figure. That's why your y axes are so narrow.
You could try to define the figure size beforehand, or determine the figure size based on how many subplots you have:
n_plots = roll_df.shape[1]
fig, axes = plt.subplots(n_plots, 1, figsize=(8, 4 * n_plots), tight_layout=True)
# Then your usual part, but plot on the created axes
for i in range(n_plots):
name = roll_df.columns[i]
axes[i].plot(roll_df[name])
axes[i].title(name, y=0)
axes[i].yticks([])
axes[i].xticks([])
plt.show()

Categories

Resources