How to change Bar-Chart Figure Size [duplicate] - matplotlib

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.

Related

How to se BG color over an Histogram graph in matplotlb [duplicate]

I am making a scatter plot in matplotlib and need to change the background of the actual plot to black. I know how to change the face color of the plot using:
fig = plt.figure()
fig.patch.set_facecolor('xkcd:mint green')
My issue is that this changes the color of the space around the plot. How to I change the actual background color of the plot?
Use the set_facecolor(color) method of the axes object, which you've created one of the following ways:
You created a figure and axis/es together
fig, ax = plt.subplots(nrows=1, ncols=1)
You created a figure, then axis/es later
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1) # nrows, ncols, index
You used the stateful API (if you're doing anything more than a few lines, and especially if you have multiple plots, the object-oriented methods above make life easier because you can refer to specific figures, plot on certain axes, and customize either)
plt.plot(...)
ax = plt.gca()
Then you can use set_facecolor:
ax.set_facecolor('xkcd:salmon')
ax.set_facecolor((1.0, 0.47, 0.42))
As a refresher for what colors can be:
matplotlib.colors
Matplotlib recognizes the following formats to specify a color:
an RGB or RGBA tuple of float values in [0, 1] (e.g., (0.1, 0.2, 0.5) or (0.1, 0.2, 0.5, 0.3));
a hex RGB or RGBA string (e.g., '#0F0F0F' or '#0F0F0F0F');
a string representation of a float value in [0, 1] inclusive for gray level (e.g., '0.5');
one of {'b', 'g', 'r', 'c', 'm', 'y', 'k', 'w'};
a X11/CSS4 color name;
a name from the xkcd color survey; prefixed with 'xkcd:' (e.g., 'xkcd:sky blue');
one of {'tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple', 'tab:brown', 'tab:pink', 'tab:gray', 'tab:olive', 'tab:cyan'} which are the Tableau Colors from the ‘T10’ categorical palette (which is the default color cycle);
a “CN” color spec, i.e. 'C' followed by a single digit, which is an index into the default property cycle (matplotlib.rcParams['axes.prop_cycle']); the indexing occurs at artist creation time and defaults to black if the cycle does not include color.
All string specifications of color, other than “CN”, are case-insensitive.
One method is to manually set the default for the axis background color within your script (see Customizing matplotlib):
import matplotlib.pyplot as plt
plt.rcParams['axes.facecolor'] = 'black'
This is in contrast to Nick T's method which changes the background color for a specific axes object. Resetting the defaults is useful if you're making multiple different plots with similar styles and don't want to keep changing different axes objects.
Note: The equivalent for
fig = plt.figure()
fig.patch.set_facecolor('black')
from your question is:
plt.rcParams['figure.facecolor'] = 'black'
Something like this? Use the axisbg keyword to subplot:
>>> from matplotlib.figure import Figure
>>> from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
>>> figure = Figure()
>>> canvas = FigureCanvas(figure)
>>> axes = figure.add_subplot(1, 1, 1, axisbg='red')
>>> axes.plot([1,2,3])
[<matplotlib.lines.Line2D object at 0x2827e50>]
>>> canvas.print_figure('red-bg.png')
(Granted, not a scatter plot, and not a black background.)
Simpler answer:
ax = plt.axes()
ax.set_facecolor('silver')
If you already have axes object, just like in Nick T's answer, you can also use
ax.patch.set_facecolor('black')
The easiest thing is probably to provide the color when you create the plot :
fig1 = plt.figure(facecolor=(1, 1, 1))
or
fig1, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, facecolor=(1, 1, 1))
One suggestion in other answers is to use ax.set_axis_bgcolor("red"). This however is deprecated, and doesn't work on MatPlotLib >= v2.0.
There is also the suggestion to use ax.patch.set_facecolor("red") (works on both MatPlotLib v1.5 & v2.2). While this works fine, an even easier solution for v2.0+ is to use
ax.set_facecolor("red")
In addition to the answer of NickT, you can also delete the background frame by setting it to "none" as explain here: https://stackoverflow.com/a/67126649/8669161
import matplotlib.pyplot as plt
plt.rcParams['axes.facecolor'] = 'none'
I think this might be useful for some people:
If you want to change the color of the background that surrounds the figure, you can use this:
fig.patch.set_facecolor('white')
So instead of this:
you get this:
Obviously you can set any color you'd want.
P.S. In case you accidentally don't see any difference between the two plots, try looking at StackOverflow using darkmode.

Relocating legend from GeoPandas plot

I'm plotting a map with legends using the GeoPandas plotting function. When I plot, my legends appear in the upper right corner of the figure. Here is how it looks like:
I wanted to move the legends to the lower part of the graph. I would normally would have done something like this for a normal matplotlib plot:
fig, ax = plt.subplots(1, figsize=(4.5,10))
lima_bank_num.plot(ax=ax, column='quant_cuts', cmap='Blues', alpha=1, legend=True)
ax.legend(loc='lower left')
However, this modification is not taken into account.
This could be done using the legend_kwds argument:
df.plot(column='values', legend=True, legend_kwds={'loc': 'lower right'});
You can access the legend defined on the ax instance with ax.get_legend(). You can then update the location of the legend using the method set_bbox_to_anchor. This doesn't provide the same ease of use as the loc keyword when creating a legend from scratch, but does give control over placement. So, for your example, something like:
leg = ax.get_legend()
leg.set_bbox_to_anchor((0., 0., 0.2, 0.2))
A bit of documentation of set_bbox_to_anchor, though I don't find it extraordinarily helpful.
If you have a horizontal legend and you're trying to simply reduce the gap between the legend and plot, I recommend the colorbar approach detailed at https://gis.stackexchange.com/a/330175/32531 along with passing the pad legend_kwd argument:
legend_kwds={"orientation": "horizontal", "pad": 0.01}

Python matplotlib: fractional logscale

I would like to plot some data with a fractional logscale, such that the y axis has the ticks at 10^(-0.1), 10^(-0.2), 10^(-0.3), etc.
The problem is that when I plot my data, there are only ticks at 10^0 and 10^-1, which leaves the slope of the line too slight to see.
Is is possible to set a fractional logscale this way?
Thanks
It sounds like you want tick labels, not the tick marks in particular. In most figures, the minor tick marks are already there where you want them.
The following may then work, though I would think there's an easier way. Note that I'm applying labels to the minor tick marks only: the (two) major tick marks already have a label. Unfortunately, the fonts of the two types of tick marks are not the same; I think that's a result of the LaTeX equation usage.
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
X = np.logspace(0, 3)
Y = X**-0.2
plt.plot(X,Y)
plt.yscale('log')
yticks = np.linspace(-0.1, -0.9, 9)
ax.set_yticks(10**yticks, minor=True)
ax.set_ylim(0.1, 1)
ax.set_yticklabels(['$10^{{{:.1f}}}$'.format(ytick) for ytick in yticks], minor=True)
plt.show()
which results in:
For the issue of the different label fonts, you can manually change the major tick labels:
ax.set_yticks([1, 0.1])
ax.set_yticklabels(['$10^0$', '$10^{-1}$'])
(and probably the same for the x-axis).

Reducing the distance between two boxplots

I'm drawing the bloxplot shown below using python and matplotlib. Is there any way I can reduce the distance between the two boxplots on the X axis?
This is the code that I'm using to get the figure above:
import matplotlib.pyplot as plt
from matplotlib import rcParams
rcParams['ytick.direction'] = 'out'
rcParams['xtick.direction'] = 'out'
fig = plt.figure()
xlabels = ["CG", "EG"]
ax = fig.add_subplot(111)
ax.boxplot([values_cg, values_eg])
ax.set_xticks(np.arange(len(xlabels))+1)
ax.set_xticklabels(xlabels, rotation=45, ha='right')
fig.subplots_adjust(bottom=0.3)
ylabels = yticks = np.linspace(0, 20, 5)
ax.set_yticks(yticks)
ax.set_yticklabels(ylabels)
ax.tick_params(axis='x', pad=10)
ax.tick_params(axis='y', pad=10)
plt.savefig(os.path.join(output_dir, "output.pdf"))
And this is an example closer to what I'd like to get visually (although I wouldn't mind if the boxplots were even a bit closer to each other):
You can either change the aspect ratio of plot or use the widths kwarg (doc) as such:
ax.boxplot([values_cg, values_eg], widths=1)
to make the boxes wider.
Try changing the aspect ratio using
ax.set_aspect(1.5) # or some other float
The larger then number, the narrower (and taller) the plot should be:
a circle will be stretched such that the height is num times the width. aspect=1 is the same as aspect=’equal’.
http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.set_aspect
When your code writes:
ax.set_xticks(np.arange(len(xlabels))+1)
You're putting the first box plot on 0 and the second one on 1 (event though you change the tick labels afterwards), just like in the second, "wanted" example you gave they are set on 1,2,3.
So i think an alternative solution would be to play with the xticks position and the xlim of the plot.
for example using
ax.set_xlim(-1.5,2.5)
would place them closer.
positions : array-like, optional
Sets the positions of the boxes. The ticks and limits are automatically set to match the positions. Defaults to range(1, N+1) where N is the number of boxes to be drawn.
https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.boxplot.html
This should do the job!
As #Stevie mentioned, you can use the positions kwarg (doc) to manually set the x-coordinates of the boxes:
ax.boxplot([values_cg, values_eg], positions=[1, 1.3])

Change figsize in matplotlib polar contourf

I am using the following example Example to create two polar contour subplots. When I create as the pdf there is a lot of white space which I want to remove by changing figsize.
I know how to change figsize usually but I am having difficulty seeing where to put it in this code example. Any guidance or hint would be greatly appreciated.
Many thanks!
import numpy as np
import matplotlib.pyplot as plt
#-- Generate Data -----------------------------------------
# Using linspace so that the endpoint of 360 is included...
azimuths = np.radians(np.linspace(0, 360, 20))
zeniths = np.arange(0, 70, 10)
r, theta = np.meshgrid(zeniths, azimuths)
values = np.random.random((azimuths.size, zeniths.size))
#-- Plot... ------------------------------------------------
fig, ax = plt.subplots(subplot_kw=dict(projection='polar'))
ax.contourf(theta, r, values)
plt.show()
Another way to do this would be to use the figsize kwarg in your call to plt.subplots.
fig, ax = plt.subplots(figsize=(6,6), subplot_kw=dict(projection='polar')).
Those values are in inches, by the way.
You can easily just put plt.figsize(x,y) at the beginning of the code, and it will work. plt.figsize changes the size of all future plots, not just the current plot.
However, I think your problem is not what you think it is. There tends to be quite a bit of whitespace in generated PDFs unless you change options around. I usually use
plt.savefig( 'name.pdf', bbox_inches='tight', pad_inches=0 )
This gives as little whitespace as possible. bbox_inches='tight' tries to make the bounding box as small as possible, while pad_inches sets how many inches of whitespace there should be padding it. In my case I have no extra padding at all, as I add padding in whatever I'm using the figure for.