matplotlib: autofmt_xdate doesn't work for multiple rows - python-3.x

I am using the autofmt_xdate() to get better looking x-axis (in date) like below:
fig, ax = plt.subplots(1,2, figsize=(12, 5))
ax[0].plot(my_df[['my_time']], my_df[['field_A']])
ax[0].set_xlable('time')
fig.autofmt_xdate()
This works fine. However, if I do two rows like below:
fig, ax = plt.subplots(2,2, figsize=(12, 5))
ax[0][0].plot(my_df[['my_time']], my_df[['field_A']])
ax[0][0].set_xlable('time')
fig.autofmt_xdate()
Then the labels and ticks of ax[0][0] x-axis disappeared. Any idea what I did wrong? Thanks!

You didn't do anything wrong here. What you see is the expected behaviour of fig.autofmt_xdate().
As the documentation says,
The ticklabels are often long, and it helps to rotate them on the bottom subplot and turn them off on other subplots, as well as turn off xlabels.

Related

How to make the scatterplot square than rectangle? [duplicate]

This question already has answers here:
How can I set the aspect ratio in matplotlib?
(7 answers)
Closed last month.
I created a scatter plot which has equal min, max, steps for both x and y axis. However the result keeps making my graph look rectangle rather than a square. How can I fix this?
'''
ax = ctrl_ra.plot.scatter(x='Control', y='Infection(Ra)', color='black', alpha=0.5)
ax2 = df_sig.plot.scatter(ax=ax, x= 'Control', y='Infection(Ra)', color='red', alpha=0.5, s=5)
#Set the x-axis and y-axis scales
ax.set_xticks(np.arange(0,21,5))
ax.set_yticks(np.arange(0,21,5))
ax2.set_xticks(np.arange(0,21,5))
ax2.set_yticks(np.arange(0,21,5))
plt.show()
'''
This is what I got when I ran my code.
At first I thought it was the axis scale and/or size but it wasn't so I'm not sure where to go about to fix this problem.
Any help is appreciated. Thank you.
It is the figure size, not axes scale.
Try adding
plt.figure(figsize=(12, 12))
before plotting. Or, better, use
fig, ax = plt.subplots(figsize=(12, 12))

mini scatter matrix using subplots as a loop

I have a dataset with 25 columns and wanted to examine scatter plots. I first looked at it with
Seaborn scatterplot() but this is too messy and there are too many charts to make sense of it all.
So instead I wanted to iterate a single column over all of the columns.
I created this simple loop:
for col in ds_num.columns:
plt.figure()
sns.scatterplot(x='initial_term',y=col,hue='logo_renewal',data=ds_num)
plt.show()
This worked but it gave it in a one column shape. I'd like it to plot for a few in each row so I tried this instead:
for idx, col in enumerate(ds_num.columns):
fig = plt.figure(figsize=(20,16))
ax[idx+1] = fig.add_subplot(5,5,idx+1)
sns.scatterplot(x='initial_term',y=col,hue='logo_renewal',data=ds_num,ax=ax[idx])
plt.show()
But now I got TypeError: 'AxesSubplot' object does not support item assignment
Any suggestions? Thanks
Found the answer with the help of subplots:
fig, axs = plt.subplots(5,5,figsize=(20,20))
cols = ds_num.columns
for ax, col in zip(axs.flatten(),cols):
sns.scatterplot(x='initial_term',y=col,hue='logo_renewal',data=ds_num,ax=ax,legend=False)
plt.tight_layout()
Notice I removed the legend as it took too much space, this is of course not mandatory

matplotlib histogram bins not reflecting data [duplicate]

I can't figure out how to rotate the text on the X Axis. Its a time stamp, so as the number of samples increase, they get closer and closer until they overlap. I'd like to rotate the text 90 degrees so as the samples get closer together, they aren't overlapping.
Below is what I have, it works fine with the exception that I can't figure out how to rotate the X axis text.
import sys
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import datetime
font = {'family' : 'normal',
'weight' : 'bold',
'size' : 8}
matplotlib.rc('font', **font)
values = open('stats.csv', 'r').readlines()
time = [datetime.datetime.fromtimestamp(float(i.split(',')[0].strip())) for i in values[1:]]
delay = [float(i.split(',')[1].strip()) for i in values[1:]]
plt.plot(time, delay)
plt.grid(b='on')
plt.savefig('test.png')
This works for me:
plt.xticks(rotation=90)
Many "correct" answers here but I'll add one more since I think some details are left out of several. The OP asked for 90 degree rotation but I'll change to 45 degrees because when you use an angle that isn't zero or 90, you should change the horizontal alignment as well; otherwise your labels will be off-center and a bit misleading (and I'm guessing many people who come here want to rotate axes to something other than 90).
Easiest / Least Code
Option 1
plt.xticks(rotation=45, ha='right')
As mentioned previously, that may not be desirable if you'd rather take the Object Oriented approach.
Option 2
Another fast way (it's intended for date objects but seems to work on any label; doubt this is recommended though):
fig.autofmt_xdate(rotation=45)
fig you would usually get from:
fig = plt.gcf()
fig = plt.figure()
fig, ax = plt.subplots()
fig = ax.figure
Object-Oriented / Dealing directly with ax
Option 3a
If you have the list of labels:
labels = ['One', 'Two', 'Three']
ax.set_xticks([1, 2, 3])
ax.set_xticklabels(labels, rotation=45, ha='right')
In later versions of Matplotlib (3.5+), you can just use set_xticks alone:
ax.set_xticks([1, 2, 3], labels, rotation=45, ha='right')
Option 3b
If you want to get the list of labels from the current plot:
# Unfortunately you need to draw your figure first to assign the labels,
# otherwise get_xticklabels() will return empty strings.
plt.draw()
ax.set_xticks(ax.get_xticks())
ax.set_xticklabels(ax.get_xticklabels(), rotation=45, ha='right')
As above, in later versions of Matplotlib (3.5+), you can just use set_xticks alone:
ax.set_xticks(ax.get_xticks(), ax.get_xticklabels(), rotation=45, ha='right')
Option 4
Similar to above, but loop through manually instead.
for label in ax.get_xticklabels():
label.set_rotation(45)
label.set_ha('right')
Option 5
We still use pyplot (as plt) here but it's object-oriented because we're changing the property of a specific ax object.
plt.setp(ax.get_xticklabels(), rotation=45, ha='right')
Option 6
This option is simple, but AFAIK you can't set label horizontal align this way so another option might be better if your angle is not 90.
ax.tick_params(axis='x', labelrotation=45)
Edit:
There's discussion of this exact "bug" but a fix hasn't been released (as of 3.4.0):
https://github.com/matplotlib/matplotlib/issues/13774
Easy way
As described here, there is an existing method in the matplotlib.pyplot figure class that automatically rotates dates appropriately for you figure.
You can call it after you plot your data (i.e.ax.plot(dates,ydata) :
fig.autofmt_xdate()
If you need to format the labels further, checkout the above link.
Non-datetime objects
As per languitar's comment, the method I suggested for non-datetime xticks would not update correctly when zooming, etc. If it's not a datetime object used as your x-axis data, you should follow Tommy's answer:
for tick in ax.get_xticklabels():
tick.set_rotation(45)
Try pyplot.setp. I think you could do something like this:
x = range(len(time))
plt.xticks(x, time)
locs, labels = plt.xticks()
plt.setp(labels, rotation=90)
plt.plot(x, delay)
Appart from
plt.xticks(rotation=90)
this is also possible:
plt.xticks(rotation='vertical')
I came up with a similar example. Again, the rotation keyword is.. well, it's key.
from pylab import *
fig = figure()
ax = fig.add_subplot(111)
ax.bar( [0,1,2], [1,3,5] )
ax.set_xticks( [ 0.5, 1.5, 2.5 ] )
ax.set_xticklabels( ['tom','dick','harry'], rotation=45 ) ;
If you want to apply rotation on the axes object, the easiest way is using tick_params. For example.
ax.tick_params(axis='x', labelrotation=90)
Matplotlib documentation reference here.
This is useful when you have an array of axes as returned by plt.subplots, and it is more convenient than using set_xticks because in that case you need to also set the tick labels, and also more convenient that those that iterate over the ticks (for obvious reasons)
If using plt:
plt.xticks(rotation=90)
In case of using pandas or seaborn to plot, assuming ax as axes for the plot:
ax.set_xticklabels(ax.get_xticklabels(), rotation=90)
Another way of doing the above:
for tick in ax.get_xticklabels():
tick.set_rotation(45)
My answer is inspired by cjohnson318's answer, but I didn't want to supply a hardcoded list of labels; I wanted to rotate the existing labels:
for tick in ax.get_xticklabels():
tick.set_rotation(45)
The simplest solution is to use:
plt.xticks(rotation=XX)
but also
# Tweak spacing to prevent clipping of tick-labels
plt.subplots_adjust(bottom=X.XX)
e.g for dates I used rotation=45 and bottom=0.20 but you can do some test for your data
import pylab as pl
pl.xticks(rotation = 90)
To rotate the x-axis label to 90 degrees
for tick in ax.get_xticklabels():
tick.set_rotation(45)
It will depend on what are you plotting.
import matplotlib.pyplot as plt
x=['long_text_for_a_label_a',
'long_text_for_a_label_b',
'long_text_for_a_label_c']
y=[1,2,3]
myplot = plt.plot(x,y)
for item in myplot.axes.get_xticklabels():
item.set_rotation(90)
For pandas and seaborn that give you an Axes object:
df = pd.DataFrame(x,y)
#pandas
myplot = df.plot.bar()
#seaborn
myplotsns =sns.barplot(y='0', x=df.index, data=df)
# you can get xticklabels without .axes cause the object are already a
# isntance of it
for item in myplot.get_xticklabels():
item.set_rotation(90)
If you need to rotate labels you may need change the font size too, you can use font_scale=1.0 to do that.

How to prevent from drawing overlapping axis ticks when adding a line to scatter plot?

fig, ax = plt.subplots()
ax = fig.add_subplot(111)
ax.scatter(X[1],y)
y_projection = X.dot(theta_after)
ax.plot(X[1], y_projection)
plt.show()
Above is my code. What I'm trying to do is basically fitting a line to the data. I use gradient descent method to find the suitable theta.
The problem I came across is that the code above created two x-axis and y-axis and that they were overlapping on each other
This is the result generated from the above code. I'm not allowed to embed a pic now, please click on this to open the pic.
X - is a 97*2 matrix in which the first column is all 1.
You are creating an extra Axes with your second line. Just remove the following line:
ax = fig.add_subplot(111)
You already have an Axes when you run fig, ax = plt.subplots()

matplotlib dynamic number of subplot

I am trying to get a subplot using matplotlib, with number of subplots calculated in runtime (as pnum varies in the example below)
pnum = len(args.m)
f, (ax1, ax2) = plt.subplots(pnum, sharex=True, sharey=True)
ax1.plot(x,ptp, "#757578",label="Total")
ax2.fill_between(x,dxyp,facecolor="C0", label="$d_{xy}$")
This example, obviously, only work, when pnum=2. So, I need to do some thing else.
I have checked the accepted answer of this question, but this is plotting same thing in all the plots.
To create a dynamic number of subplots you may decide not to specify the axes individually, but as an axes array
pnum = len(args.m)
fig, ax_arr = plt.subplots(pnum, sharex=True, sharey=True)
ax_arr is then a numpy array.
You can then do something for each axes in a loop.
for ax in ax_arr.flatten():
ax.plot(...)

Resources