How can I get length of axis' major ticks in matplotlib? - python

I know that I can set length of ticks with length parameter of AxesSubplot.tick_params() method.
How may I determine the actual length of major ticks of certain axis?
Please assume the length may be altered.

The default length of the ticks is determined by the xtick.major.size or ytick.major.size, or the xtick.minor.size or ytick.minor.size rcParams.
You may find out programmatically via
import matplotlib.pyplot as plt
print(plt.rcParams["xtick.major.size"])
This prints in the usual case 3.5 (size in points).
You may equally use those the rcParams to set the length
import matplotlib.pyplot as plt
plt.rcParams["xtick.major.size"] = 6
This will work in all cases where you create the axes yourself and have not (yet) changed the length e.g. via the tick_params method.
Otherwise, you can find out the tick length via
ax.xaxis.majorTicks[0].tick1line.get_markersize()
where ax is the axes in question.

Related

Use scientific notation for Python plots by default

Simple question: how do I get Python to use scientific notation in its plots by default? From various posts on SO I can write something like
from numpy import linspace
import matplotlib.pyplot as plt
plt.figure()
plt.plot(linspace(1e6,2e6),linspace(1e6,1e7))
plt.figure()
plt.plot(linspace(8e6,9e6),linspace(2e6,2.5e7))
plt.ticklabel_format(style='sci', axis='both', scilimits=(-2,2))
plt.show()
but ticklabel_format only acts on the last plot generated by matplotlib. (If plt.ticklabel_format() is put at the beginning of the code, I also get a blank figure showing the x,y axes.)
You can modify the default behaviour of matplotlib by edditing your "rc" file. See Customizing matplotlib.
In you case, it looks like you could adjust the item:
axes.formatter.limits : -2, 2 # use scientific notation if log10
# of the axis range is smaller than the
# first or larger than the second

Matplotlib subplots ticks and title [duplicate]

This question already has answers here:
Python Matplotlib figure title overlaps axes label when using twiny
(8 answers)
Closed 3 years ago.
I have a simple plot in matplotlib and I would like to increase the distance between the title and the plot (without using suptitle because it does not work on the version I use on a server). How to do that ?
With matplotlib 2.2+, you can use the keyword argument pad:
ax.set_title('Title', pad=20)
Adjust pad until you're happy with the axis title position. The advantage of this method over using rcParams is that it only changes this one axis title.
There doesn't seem to be a clean way to set this directly (but might be worth a feature request to add that), however the title is just a text artist, so you can reach in and change it.
#ax = plt.gca()
ttl = ax.title
ttl.set_position([.5, 1.05])
#plt.draw()
should do the trick. Tune the 1.05 to your liking.
You can just pass y parameter into plt.suptitle method:
plt.suptitle('Amazing Stats', size=16, y=1.12);
Using rcParams:
from matplotlib import rcParams
rcParams['axes.titlepad'] = 20
where 20 is the padding between the plot and the title.
From https://matplotlib.org/users/customizing.html
Another possibility is to reduce the relative size of the plot with respect to the whole figure window. In that way the distance between title and plot increases.
Before showing the plot, i.e. before plt.show(), write following command:
#The standard value of 'top' is 0.9,
#tune a lower value, e.g., 0.8
plt.subplots_adjust(top=0.8)
This method has the advantage over #CanCeylan method that the title never goes out of the figure window; because if the title is large enough, then moving it upwards through the parameter y in suptitle might move the title outside the figure. (as it happened to me ;))

Using a colormap for matplotlib line plots

I’d like to employ the reverse Spectral colormap ,
https://matplotlib.org/examples/color/colormaps_reference.html
for a lineplot.
This works fine with a hex bin plot::
color_map = plt.cm.Spectral_r
image = plt.hexbin(x,y,cmap=color_map)
but when I do
ax1.plot(x,y, cmp=color_map)
this gives me::
AttributeError: Unknown property cmap
Note, I just want to set the colormap and let matplotliob do the rest; i.e. I don't want to have a color=' argument in the .plot command.
You can have a look at this solution - the third variant is what you want:
https://stackoverflow.com/a/57227821/5972778
You need to know how many lines you're plotting in advance, as otherwise it doesn't know how to choose the colours from the range.
I think that seaborn's color_palette function is very convenient for this purpose. It can be used in a with statement to temporarily set the color cycle for a plot or set of plots.
For example:
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
with sns.color_palette("Spectral", n_colors=10):
plt.plot(np.random.rand(5, 10))
You can use with any predefined matplotlib or seaborn colormap, or provide a custom sequence of colors.

Vertical spacing between xticklabel to the bottom of x-axis

I am wondering if there could be any way to change the spacing between xticklabel (i.e. $\widetilde{M}) and the bottom of x-axis? In my case the spacing is too small so that the tilde above M (left bar) becomes invisible. BTW I am using pandas' plot function to generate the bar plot.
Since Pandas uses the Matplotlib library for all the plotting, you can change this setting through rcParams. First import:
from matplotlib import rcParams
and then (before plotting anything) change the padding above the xticks:
rcParams['xtick.major.pad'] = 20
Assuming you import matplotlib.pyplot as plt You can manipulate the pyplot object via the tick_params method and pad arg. E.g.:
plt.tick_params(pad=10)

Why do matplotlib subplots start with 1

When creating subplots with matplotlib you need to start with 1, while most other python things start with zero. So to create the very first subplot (top left)
ax = fig.add_subplot(3,4,1)
Where I would have expected 0 to be the first subplot
ax = fig.add_subplot(3,4,0)
I've seen the explanation "we got this from matlab" but that seems like a particularly unsatisfying answer.
The answer really is: "it's meant for matlab-compatibility". There is one minor advantage in terms of the shortcut integer notation (subplot(231) instead of subplot(2,3,1)). You can't express a 0-based system that way without using strings instead. However, that shortcut notation is generally a bad idea, and should only ever be used in an interactive scenario where readability isn't a concern.
As #Cong Ma mentioned, in most cases, you'd use subplots and index a 2D array instead of the matlab-style numerical system. It's a better approach all-around.
For example:
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=2, ncols=3)
axes[0, 0].plot(range(10))
plt.show()
It's not exactly identical, as it also adds all of the subplots, but you can always hide the ones you don't want to be visible (ax.axis('off') or ax.set(visible=False)).

Categories