matplotlib tick labels position relative to axes - matplotlib

I set matplotlib to put ticks outside the plot area but now they overlap on the corresponding labels. the tick_params method does not provide any option to set the corresponding labels position.
So I guess I will have to write my own function using text() method. In the meanwhile does any one has a better suggestion?

To shift the tick labels relative to the ticks use pad. Compare
ax.tick_params(direction='out', pad=5)
plt.draw()
with
ax.tick_params(direction='out', pad=15)
plt.draw()

Related

How do I stretch our the horizontal axis of a matplotlib pyplot?

I'm creating a colour map which has 64 horizontal data points and 3072 vertical. When I plot it, the scaling on both axes is the same and so the horizontal axis is super squished and tiny, and I can't get any information from it. I've tried changing the figsize parameter but nothing changes the actual plot, only the image that contains it. Any ideas on how to change my plot so that the actual length of the axes are the same? Below is my plotting code:
def plot_plot(self, data, title="Pixel Plot"):
pixel_plot = plt.imshow(data)
plt.title(title)
plt.colorbar(pixel_plot)
plt.show(pixel_plot)
thanks in advance!
I think you want the aspect option in plt.imshow().
So something like plt.imshow(data, aspect=0.1) or plt.imshow(data, aspect='equal')
See this solution: https://stackoverflow.com/a/13390798/12133280

Matplotlib widget, secondary y axis, twinx

i use jupyterlab together with matplotlib widgets. I have ipywidgets installed.
My goal is to choose which y-axis data is displayed in the bottom of the figure.
When i use the interactive tool to see the coordinates i get only the data of the right y-axis displayed. Both would be really nice^^ My minimal code example:
import matplotlib.pyplot as plt
import numpy as np
%matplotlib widgets
x=np.linspace(0,100)
y=x**2
y2=x**3
fig,ax=plt.subplots()
ax2=ax.twinx()
ax.plot(x,y)
ax2.plot(x,y2)
plt.show()
With this example you might ask why not to plot them to the same y-axis but thats why it is a minimal example. I would like to plot data of different units.
To choose which y-axis is used, you can set the zorder property of the axes containing this y-axis to a higher value than that of the other axes (0 is the default):
ax.zorder = 1
However, that will cause this Axes to obscure the other Axes. To counteract this, use
ax.set_facecolor((0, 0, 0, 0))
to make the background color of this Axes transparent.
Alternatively, use the grab_mouse function of the figure canvas:
fig.canvas.grab_mouse(ax)
See here for the (minimal) documentation for grab_mouse.
The reason this works is this:
The coordinate line shown below the figure is obtained by an event callback which ultimately calls matplotlib.Axes.format_coord() on the axes instance returned by the inaxes property of the matplotlib events that are being generated by your mouse movement. This Axes is the one returned by FigureCanvasBase.inaxes() which uses the Axes zorder, and in case of ties, chooses the last Axes created.
However, you can tell the figure canvas that one Axes should receive all mouse events, in which case this Axes is also set as the inaxes property of generated events (see the code).
I have not found a clean way to make the display show data from both Axes. The only solution I have found would be to monkey-patch NavigationToolbar2._mouse_event_to_message (also here) to do what you want.

TramineR legend position and axis

I'm working with TraMineR and I don't know how to arrange my plot. So basically what i would like to have the legend under the plot and to remove the space between the x and y axis. Any help is welcomed.
The plot:
Sample code:
seqdplot(Activities.seq, with.legend=FALSE)
legend("bottom", legend=attr(Activities.seq, "labels"),
fill=attr(Activities.seq, "cpal"),
inset=-.1, bty="o", xpd=NA, cex=.75,ncol=3)
The family of seqplot functions offers a series of arguments to control the legend as well as the axes. Look at the help page of seqplot (and of plot.stslist.statd for specific seqdplot parameters).
For instance, you can suppress the x-axis with axes=FALSE, and the y-axis with yaxis=FALSE.
To print the legend you can let seqdplot display it automatically using the default with.legend=TRUE option and control it with for examples cex.legend for the font size, ltext for the text. You can also use the ncol argument to set the number of columns in the legend.
The seqplot functions use by default layout to organize the graphic area between the plots and the legend. If you need more fine tuning (e.g. to change the default par(mar=c(5.1,4.1,4.1,2.1)) margins around the plot and the legend), you should create separately the plot(s) and the legend and then organize them yourself using e.g. layout or par(mfrow=...). In that case, the separate graphics should be created by setting with.legend=FALSE, which prevents the display of the legend and disables the automatic use of layout.
The color legend is easiest obtained with seqlegend.
I illustrate with the mvad data that ships with TraMineR. First the default plot with the legend. Note the use of border=NA to suppress the too many vertical black lines.
library(TraMineR)
data(mvad)
mvad.scode <- c("EM", "FE", "HE", "JL", "SC", "TR")
mvad.seq <- seqdef(mvad, 17:86,
states = mvad.scode,
xtstep = 6)
# Default plot with the legend,
seqdplot(mvad.seq, border=NA)
Now, we suppress the x and y axes and modify the display of the legend
seqdplot(mvad.seq, border=NA,
axes=FALSE, yaxis=FALSE, ylab="",
cex.legend=1.3, ncol=6, legend.prop=.11)
Here is how you can control the space between the plot and the x and y axes
seqdplot(mvad.seq, border=NA, yaxis=FALSE, xaxis=FALSE, with.legend=FALSE)
axis(2, line=-1)
axis(1, line=0)
Creating the legend separately and reducing the left, top, and right margins around the legend
op <- par(mar=c(5.1,0.1,0.1,0.1))
seqlegend(mvad.seq, ncol=2, cex=2)
par(op)

How do I display only every nth axis label

I am using matplotlib to make a scatter plot, and the x-axis labels are running together to the point they are illegible. Here's all the relevant code:
plt.xticks(rotation=30)
plt.scatter(x,y)
plt.show()
x and y are lists of x-axis values and y-axis values, respectively.
This SO post (matplotlib: how to prevent x-axis labels from overlapping each other) asks the same question, but if there's an answer anywhere in there, I can't tease it out.
This SO post (Cleanest way to hide every nth tick label in matplotlib colorbar?) asks a similar question in the context of colorbars. All of the responses that seem to work for people are of the form
for label in cbar.ax.xaxis.get_ticklabels()[::2]:
label.set_visible(False)
or
plt.setp(cbar.ax.get_xticklabels()[::2], visible=False)
where cbar is the asker's colorbar object. Every time I try to adapt these solutions to my case, for example
plt.xticks(rotation=30)
plot = plt.scatter(x,y)
plt.setp(plot.get_xticklabels()[::2], visible=False)
plt.show()
I get errors like
AttributeError: 'PathCollection' object has no attribute 'get_xticklabels'.
Similar to the above, if I try plot.ax.get_xticklabels() I get AttributeError: 'PathCollection' object has no attribute 'ax', etc.
How do I show only every nth axis label?
Edit This worked: first, set all labels to not visible, then make every N labels visible
plot = plt.scatter(x,y)
plt.setp(plot.axes.get_xticklabels(), visible=False)
plt.setp(plot.axes.get_xticklabels()[::5], visible=True)
The above does every 5th label; change it to whatever you need.

Change the labels of a colorbar from increasing to decreasing values

I'd like to change the labels for the colorbar from increasing to decreasing values. When I try to do this via vmin and vmax I get the error message:
minvalue must be less than or equal to maxvalue
So, for example I'd like the colorbar to start at 20 on the left and go up to 15 on the right.
This is my code for the colorbar so far, but in this example the values go from 15 to 20 and I'd like to reverse that order:
cmap1 = mpl.cm.YlOrBr_r
norm1 = mpl.colors.Normalize(15,20)
cb1 = mpl.colorbar.ColorbarBase(colorbar1, cmap=cmap1, norm=norm1, orientation='horizontal')
cb1.set_label('magnitude')
The colorbars displayed below are probably not exactly like yours, as they are just example colorbars to function as a proof of concept.
In the following I assume you have a colorbar similar to this, with increasing values to the right:
Method 1: Inverting the x-axis
Inverts the whole x-axis of the colorbar
If you want to invert the x-axis, meaning that the values on the x-axis are descending to the right, making the colorbar "mirrored", you can make use of the ColorbarBase's ax attribute:
cb1 = mpl.colorbar.ColorbarBase(colorbar1,
cmap=cmap1,
norm=norm1,
orientation='horizontal')
cb1.ax.invert_xaxis()
This gives.the output below.
It is also possible to change the number of ticklabels by setting the colorbars locator. Here the MultipleLocator is used, although you can use many other locators as well.
from matplotlib.ticker import MultipleLocator
cb1.locator = MultipleLocator(1) # Show ticks only for each multiple of 1
cb1.update_ticks()
cb1.ax.invert_xaxis()
Method 2: Using custom ticklabels
Reverses the order of the ticklabels, keeping the orientation of the colorbar
If you want the orientation of the colorbar itself as it is, and only reverse the order in which the ticklabels appear, you can use the set_ticks and set_ticklabels methods. This is more of a "brute force" approach than the previous solution.
cb1.set_ticks(np.arange(15, 21))
cb1.set_ticklabels(np.arange(20, 14, -1))
This gives the colorbar seen below. Note that the colors are kept intact, only the tick locations and ticklabels have changed.
An alternative solution for producing the colorbar in Method 2:
cmap1 = cmap1.reversed()
cb1.ax.invert_yaxis()
works for me: variable_you_want.ax.invert_yaxis()