I have produced the graph shown below as intended with matplotlib and Pandas except two problems:
I can't get rid of the x axes labels (Year) for the three plots at the top (things I have tried are commented out in the code attached), and I could not centre the y axis label.
It seem trivial but I can't get it to work.
Any suggestions?
Thanks
fig, axes = plt.subplots(nrows=4, ncols=1, sharex=True, figsize=(12, 12))
for i, crop in enumerate(['Cabbage','Green beans','Potato', 'Wheat']):
mean_irr_soil[crop].plot(kind='bar', ax=axes[i], title=crop, grid=False)
axes[i].set_ylim([0, 700]) # set limit for all y axes
axes[i].tick_params(axis='x', top='off') # remove top ticks
axes[i].tick_params(axis='y', right='off') # remove right-hand ticks
axes[i].tick_params(axis='x', labelbottom='off')
if i is not 0:
axes[i].legend_.remove() # all but top graph
# if i is not 3:
# axes[i].get_xaxis().set_visible(False) # remove axis all together
# axes[i].tick_params(axis='x', labelbottom='off')
# axes[i].set_xticklabels([]) # remove x-axis labels
axes[0].legend(bbox_to_anchor=(1.1, 1.4))
axes[2].set_ylabel('Mean irrigation requirements in mm')
You need the xlabel attribute: ax.set_xlabel("").
Related
I am using matplotlib to graph 3 time series. I want all 3 y-axes to be plotted on the right side of the graph. However I am unable to get one of the y-axis values to plot on the right side, only it's axis label.
Here is my code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import datetime as dt
import matplotlib.dates as mdates
from matplotlib.ticker import ScalarFormatter, FormatStrFormatter
from matplotlib import ticker
# Set date range for graph
df_ratios=df_ratios.loc['2017-06':'2021-12']
#-------------------------------------------------------------------
#For all Matplotlib plots, we start by creating a figure and an axes.
#-------------------------------------------------------------------
# subplot for plotting figure
fig, ax = plt.subplots()
#Similar to fig=plt.figure(figsize=(12,6))
fig.set_figwidth(12)
fig.set_figheight(6)
# Graph title
#############
fig.suptitle('Inventory-to-Sales Ratios by Industry',fontsize=20)
# LABELS: Set x label which is common / set left y-axis label / set labelcolor and labelsize to the left Y-axis
###############################################################################################################
ax.set_xlabel('Monthly: Jun 2017 - Dec. 2021')
ax.set_ylabel('Manufacturers I/S Ratio', color='red',size='x-large')
ax.tick_params(axis='y', labelcolor='red', labelsize='large')
ax.spines["right"].set_visible(True)
# Left Y-Axis: Mfg IS ratio on left Y-axis
###########################################
ax.plot(df_ratios.index, df_ratios['mfg_is_ratio'], color='red',linewidth=5.0)
ax.set_ylim(1.25,1.8)
ax.yaxis.set_major_locator(ticker.MultipleLocator(0.10))
ax.yaxis.set_label_position('right')
ax.yaxis.set_ticks_position('right')
ax.spines["right"].set_position(("axes", 1.0)) # Set second Y-axis 10% away from existing Y axis
# RIGHT Y-Axis labels: twinx sets the same x-axis for both plots / set right y-axis label / set labelcolor and labelsize to the right Y-axis
############################################################################################################################################
ax_1 = ax.twinx()
ax_1.set_ylabel('Wholesalers I/S Ratio', color='blue', size='x-large')
ax_1.tick_params(axis='y', labelcolor='blue',labelsize='large')
# FIRST Right Y-Axis plot: Wholesale IS ratio
#############################################
ax_1.plot(df_ratios.index, df_ratios['whole_is_ratio'], color='blue',linewidth=5.0)
ax_1.spines["right"].set_position(("axes", 1.08)) # Set second Y-axis 10% away from existing Y axis
ax_1.set_ylim(1.15,1.75)
ax_1.yaxis.set_major_locator(ticker.MultipleLocator(0.10))
# SECOND Right Y-Axis: Sum of Mfg+Wholesale ratios
##################################################
ax_2=ax.twinx()
ax_2.set_ylabel('Wholesalers Inventories', color='green', size='x-large')
ax_2.spines["right"].set_position(("axes", 1.18)) # Set second Y-axis 10% away from existing Y axis
ax_2.set_ylim(2.60,3.25)
ax_2.plot(df_ratios.index, df_ratios['totals'], color='green',linewidth=5.0)
ax_2.tick_params(axis='y', labelcolor='green',labelsize='large')
# Show graph:
#############
plt.show()
Here is the result:
How do I get the red y-axis values (manufacturers i/s ratio) to plot on the right side of the graph?
The problem is, when twinx() is used.
From the source code documentation:
Create a new Axes with an invisible x-axis and an independent y-axis
positioned opposite to the original one (i.e. at right).
To reverse this, just use ax.yaxis.tick_right() after all twinx() calls.
For example right before plt.show().
Red ticks should be now placed on the right side.
I have a seaborn heatmap but i need to remove the axis tick marks that show as dashes. I want the tick labels but just need to remove the dash (-) at each tick on both axes. My current code is:
sns.heatmap(df, annot=True, fmt='.2f', center=0)
I tried despine and that didnt work.
#ImportanceOfBeingEarnest had a nice answer in the comments that I wanted to add as an answer (in case the comment gets deleted).
For a heatmap:
ax = sns.heatmap(df, annot=True, fmt='.2f', center=0)
ax.tick_params(left=False, bottom=False) ## other options are right and top
If this were instead a clustermap (like here How to remove x and y axis labels in a clustermap?), you'd have an extra call:
g = sns.clustermap(...)
g.ax_heatmap.tick_params(left=False, bottom=False)
And for anyone who wanders in here looking for the related task of removing tick labels, see this answer (https://stackoverflow.com/a/26428792/3407933).
ax = sns.heatmap(df, annot=True, fmt='.2f', center=0)
ax.tick_params(axis='both', which='both', length=0)
ax is a matplotlib.axes object. All axes parameters can be changed in this object, and here's an example from the matplotlib tutorial on how to change tick parameters. both selects both x and y axis, and then their length is changed to 0, so that the ticks are not visible anymore.
How can I pass an argument to show all of the x value so one could read it? As well, how can I show many lines of data, and with alegend?
plt. plot(a, b, linewidth=2.0 )
You could display only n-th x-ticks and make a plot bigger to accomodate more labels.
df = pd.DataFrame(data=np.random.rand(10), index=pd.Series(np.random.rand(10)).astype(str)+'_index')
0
0.007017115173211574_index 0.963285
0.434969747965131_index 0.547248
0.18021258326382017_index 0.719402
0.7815848046772174_index 0.061448
0.8856299613744312_index 0.771062
0.16840431221766328_index 0.524256
0.8662531211345982_index 0.528706
0.6389453277004077_index 0.287410
0.7444490769967744_index 0.513631
0.8965709043061524_index 0.892011
plt.subplots(figsize=(20,15)) # make plot bigger
plt.plot(df.index, df[0]*2, linewidth=.9) # plot several lines
plt.plot(df.index, df[0].rename('1'),linewidth=.9) # plot several lines
plt.xticks(df.index[::2]) # tick every 2nd label on x axis.
plt.legend() # show legend
I am plotting a multipanel figure in python using a pandas dataframe. I have used the shorter version:
df1_5.plot(subplots=True, sharex=True);
which removes xtick labels on all but the bottom figure in a 5 row by 1 column figure format.
However in order to customize the plots, I was more explicit about how I plotted and used the following code:
fig, axes = plt.subplots(nrows=5, ncols=1, figsize=(8, 5))
df11_15['V11'].plot(ax=axes[0], ylim=(0, 7)); axes[0].set_title('V1')
df11_15['V12'].plot(ax=axes[1], ylim=(0, 7)); axes[1].set_title('V12')
df11_15['V13'].plot(ax=axes[2], ylim=(-0.5, 1.0)); axes[2].set_title('V13')
df11_15['V14'].plot(ax=axes[3], ylim=(-0.5,0.5)); axes[3].set_title('V14')
df11_15['V15'].plot(ax=axes[4], ylim=(-0.5, 0.5)); axes[4].set_title('V15')
I would like to remove the xticklabels from the upper four plots. Can you tell me how to do this?
I tried:
axes[3].set_axisticklabels()
but was told there was no attribute error named this.
Try this
for label in ax[3].get_xticklabels():
label.set_visible(False)
For completeness I will also provide example on how this works in a loop
# generate 2x4 matrix of subplots
fig, axs = plt.subplots(nrows=4, ncols=2)
for i,ax in enumerate(fig.axes):
# fill histograms with random numbers
ax.hist(np.random.normal(size = 100), bins=20)
# set the same xlim so that making labels invisible makes sense
ax.set_xlim([-4,4])
# make labels invisible only if "ax" is not in the last row
if not ax.is_last_row():
for label in ax.get_xticklabels():
label.set_visible(False)
Is there a way to get rid of tick labels altogether when creating an array of subplots in Matplotlib? I am currently needing to specify each plot based on the row and column of a larger data set to which the plot corresponds. I've attempted to use the ax.set_xticks([]) and the similar y-axis command, to no avail.
I recognize that it's probably an unusual request to want to make a plot with no axis data whatsoever, but that's what I need. And I need it to automatically apply to all of the subplots in the array.
You have the right method. Maybe you are not applying the set_xticks to the correct axes.
An example:
import matplotlib.pyplot as plt
import numpy as np
ncols = 5
nrows = 3
# create the plots
fig = plt.figure()
axes = [ fig.add_subplot(nrows, ncols, r * ncols + c) for r in range(0, nrows) for c in range(0, ncols) ]
# add some data
for ax in axes:
ax.plot(np.random.random(10), np.random.random(10), '.')
# remove the x and y ticks
for ax in axes:
ax.set_xticks([])
ax.set_yticks([])
This gives:
Note that each axis instance is stored in a list (axes) and then they can be easily manipulated. As usual, there are several ways of doing this, this is just an example.
Even more concise than #DrV 's answer, remixing #mwaskom's comment, a complete and total one-liner to get rid of all axes in all subplots:
# do some plotting...
plt.subplot(121),plt.imshow(image1)
plt.subplot(122),plt.imshow(image2)
# ....
# one liner to remove *all axes in all subplots*
plt.setp(plt.gcf().get_axes(), xticks=[], yticks=[]);
Note: this must be called before any calls to plt.show()
The commands are the same for subplots
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
ax1.plot([1,2])
ax1.tick_params(
axis='x', # changes apply to the x-axis
which='both', # both major and minor ticks are affected
bottom='off', # ticks along the bottom edge are off
top='off', # ticks along the top edge are off
labelbottom='off' # labels along the bottom edge are off)
)
plt.draw()
You can get rid of the default subplot x and y ticks with simply running the following codes:
fig, ax = plt.subplots()
ax.xaxis.set_major_locator(plt.NullLocator())
ax.yaxis.set_major_locator(plt.NullLocator())
for i in range(3):
ax = fig.add_subplot(3, 1, i+1)
...
Just by adding the 2 aforementioned lines just after fig, ax = plt.subplots() you can remove the default ticks.
One can remove the xticks or yticks by
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
If you want to turn off also the spines, so having no axis at all, you can use:
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)
And if you want to turn everything off at once, use:
ax.axis("off")