Matplotlib has some pretty sophisticated code figuring out how to show labels, but sometimes it cramps its labels more than looks good on presentations. Is there any way to tweek it?
For example, suppose we're plotting something against date:
figure = plt.figure(figsize=(8,1))
ax = plt.gca()
ax.set_xlim(xmin=np.datetime64('2010'), xmax=np.datetime64('2020-04-01'))
We get an x-axis like this:
But supposing we want it to show more spaced years, like this:
We can kludge it in any given case by editing the labels 'mechanically'. E.g.:
ax.set_xticks([tick for i, tick in enumerate(ax.get_xticks()) if i%2==0]) # Every other year.
ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter("%Y"))
But that's fragile, and it breaks whenever the x limits change.
Is there any way to force more spacing in the tick setup algorithm?
Oh! Found the matplotlib source code and it led me to AutoDateLocator:
ax.xaxis.set_major_locator(matplotlib.dates.AutoDateLocator(maxticks=8))
The corresponding locator for non-dates is MaxNLocator .
Related
I have a figure that I create with:
import plotly.graph_objects.Figure as go
go.Figure(data)
Now, I want to change the tick labels using a custom defined lambda function, just like I would do it for a standard matplotlib figure like this:
from matplotlib.ticker import FuncFormatter
formatter = FuncFormatter(*some lambda function*)
ax.set_xticklabels(ax.get_xticks(), rotation = 90)
ax.xaxis.set_major_formatter(formatter)
(In my particular use case, I have a matplotlib figure where my tick labels are integers that represent hours after a given start date, and I want to be able to convert them do strings in date format with my custom made lambda function)
How to do this? I have been googling for this functionallity for a long time now and found nothing that helps, while I really can't believe that there wouldn't be a simple, elegant solution for this.
I am afraid it is a little difficult to directly apply lambda function to format plotly axis since the tick label formatting rule uses d3 formatting mini-languages.
I think one way is to create the ticks by yourself and mapping that via Tickmode - Array.
I am making a program, which gives me a graph of users.
But it gives me something like this after the amount of dates has grown too high.
https://i.stack.imgur.com/iwSdc.png
I want to save them stretched, make them longer so you will be able to see dates properly.
Is there any parameter for this in plot.savefig('name')?
For example this data
Option 1
You could rotate tick labels using:
plt.xticks(rotation=90)
Option 2
or do it automaticly if you have date format:
fig.autofmt_xdate()
You can try following code:
plt.xticks(rotation=90)
It will print your x-axis values vertically.
Hope this helps!
I am plotting a timeserie with matplotlib (timeserie looks like the following):
Part of the code that i use sets major locator for each day at 0AM:
fig, ax = plt.subplots(figsize=(20, 3))
mpf.candlestick_ohlc(ax,quotes, width=0.01)
ax.xaxis_date()
ax.xaxis.set_major_locator(mpl.dates.DayLocator(interval=1) )
I would like to plot a darker background on the chart for each day between 16pm and 8am, and planning to use axvspan for that task. Considering that axvspan takes as argument axvspan(xmin, xmax) I was wondering if it would be possible to retrieve the xaxis_major_locator as a x value in order to pass it to axvspan as axvspan(xmin=major_locator-3600s, xmax=major_locator+3600s)
Edit: I found that function in the docs: http://matplotlib.org/2.0.0rc2/api/ticker_api.html#matplotlib.ticker.Locator
If anyone knows how to returns a list of ticker location from the Xaxis_major with it let me know. Thanks.
Edit2: if i use print(ax.xaxis.get_major_locator()) i receive as a return <matplotlib.dates.DayLocator object at 0x7f70f3b34090> How do i extarct a list of tick location from that?
ok found it...
majors=ax.xaxis.get_majorticklocs()
I have a quite cluttered plot with y-ticklabels that need to be very long. I've resorted into wrapping them into multiline text with textwrap. However that makes the labels overlap (or at least come too close), between categories.
I can't solve it by spacing the ticks, making the graph larger, changing font or making the text smaller. (I've already pushed these limits)
As I see it, I could resolve and make it work if I could adjust the line spacing/height to be less than what the font requests.
So imagine for simplicity's sake the following tick-label desperately needs shorter line distance between lines/line height:
from matplotlib import pyplot as plt
plt.barh(0.75, 10, height=0.5)
plt.ylim(0, 2)
plt.yticks([1], ["A very long label\nbroken into 2 line"])
plt.subplots_adjust(left=0.3)
plt.show()
I've checked plt.tick_params() the rcParams without finding any obvious solution. I'm using latex to format the text, but trying to use \hspace(0.5em} in the tick label string seemed not to work/only make things worse.
Any suggestion as to how the line spacing can be decreased would be much appreciated.
You can use the linespacing keyword in your plt.yticks line. For example:
plt.yticks([1], ["A very long label\nbroken into 2 line"],linespacing=0.5)
You can play with the exact value of linespacing to fit your needs. Hope that helps.
Here's the original output of your code:
And here it is with a linespacing of 0.5:
Attempt using this:
pylab.rcParams['xtick.major.pad']='???'
Mess around with the ??? value to get something you like. You could also try (sing the OO interface):
fig = plt.figure()
ax = fig.add_subplot(111)
ax.tick_params(axis='both', which='major', labelsize=8)
ax.set_yticks([1], ["A very long label\nbroken into 2 line"], linespacing=0.5)
plt.show()
The labelsize command will change the size of your font.
Use a combination of the above with the rcparams setup.
I'm plotting some data with matplotlib. I want the plot to focus on a specific range of x-values, so I'm using set_xlim().
Roughly, my code looks like this:
fig=plt.figure()
ax=fig.add_subplot(111)
for ydata in ydatalist:
ax.plot(x_data,y_data[0],label=ydata[1])
ax.set_xlim(left=0.0,right=1000)
plt.savefig(filename)
When I look at the plot, the x range ends up being from 0 to 12000. This occurs whether set_xlim() occurs before or after plot(). Why is set_xlim() not working in this situation?
Out of curiosity, what about switching in the old xmin and xmax?
fig=plt.figure()
ax=fig.add_subplot(111)
ax.plot(x_data,y_data)
ax.set_xlim(xmin=0.0, xmax=1000)
plt.savefig(filename)
The text of this answer was taken from an answer that was deleted almost immediately after it was posted.
set_xlim() limits the data that is displayed on the plot.
In order to change the bounds of the axis, use set_xbound().
fig=plt.figure()
ax=fig.add_subplot(111)
ax.plot(x_data,y_data)
ax.set_xbound(lower=0.0, upper=1000)
plt.savefig(filename)
In my case the following solutions alone did not work:
ax.set_xlim([0, 5.00])
ax.set_xbound(lower=0.0, upper=5.00)
However, setting the aspect using set_aspect worked, i.e:
ax.set_aspect('auto')
ax.set_xlim([0, 5.00])
ax.set_xbound(lower=0.0, upper=5.00)
I have struggled a lot with the ax.set_xlim() and couldn't get it to work properly and I found out why exactly. After setting the xlim I was setting the xticks and xticklabels (those are the vertical lines on the x-axis and their labels) and this somehow elongated the axis to the needed extent. So if the last tick was at 300 and my xlim was set at 100, it again widened the axis to the 300 just to place the tick there.
So the solution was to put it just after the troublesome code:
ax.set_xlabel(label)
ax.set_xticks(xticks)
ax.set_xticklabels(xticks, rotation=60)
ax.set_xlim(xmin=0.0, xmax=100.0)
The same thing occurred to me today. My issue was that the data was not in the right format, i.e. not floats. The limits I set (itself floats) became meaningless compared to e.g. strings. After putting float() around the data, everything worked as expected.