How to set our own yticks on a graph? - python

I want to increase the yticks upto 100. It is currently 80 but i want it to be 100.
plt.yticks(np.arange(0,100,10))
but this doesn't work.

A couple of things:
using pyplot isn't recommended (but is still possible for the sake of backwards compatibility)
setting the ticks or tick labels isn't recommended as those solutions fall apart when the axes limits changes.
So the solution is to
use the object-oriented interface
set the locator and limits directly
from matplotlib import pyplot
from matplotlib import ticker
fig, ax = pyplot.subplots(figsize=(6, 4))
ax.bar(...)
# or df.plot.bar(..., ax=ax)
ax.yaxis.set_major_locator(ticker.MultipleLocator(10))
ax.set_ylim(bottom=0, top=100)

Related

Is there a way to change the ticks for ALL the future plots with matplotlibs

I have an unusual request, but I have a question that has been bothering me for some time regarding matplotlib.
When I plot figures, even with the basic commands, for example (example), my plots do not have the same look. That is to say that in my case the ticks are systematically on the outside and only on the left and bottom edges, see:
My plot with outside ticks + only 2 axis with ticks on.
However, while looking at some ppl plots, they don't look like this, and they systematically have the four sides with ticks that are pointing inside the plot:
Plot from someone giving tips on stackoverflow
I know how to modify this for a single particular plot. But I would like to know if there is a way to specify somewhere that all my plots should have this style.
Is it possible to do so?
You can patch the Figure.add_subplot method and put your customization in there. For example:
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
_original_add_subplot = Figure.add_subplot
def new_add_subplot(*args, **kwargs):
ax = _original_add_subplot(*args, **kwargs)
ax.tick_params(left='on', right='on', top='on', bottom='on')
return ax
Figure.add_subplot = new_add_subplot
fig, ax = plt.subplots()
ax.axline((0,0), slope=1)
plt.show()
Then you could put all this in a separate package which would execute this when imported. So all you would need to do is import mplcustom. If that's still too much work, you can also put the code into sitecustomize or usercustomize modules, which will be imported automatically on startup (see Site-specific configuration hook for more information).

How do I draw borders around a matplotlib plot using object-oriented code?

I would like generate a plot with the coordinate axes in the middle of the plot area. Using matplotlib, I've managed to get as far as is shown in this sample code:
import matplotlib.pyplot as plt
xvalues = [-3,-2,-1,1,2,3]
yvalues = [2,4,-2,-4,1,-1]
fig, ax = plt.subplots()
ax.spines['bottom'].set_position('zero')
ax.spines['left'].set_position('zero')
ax.scatter(xvalues, yvalues)
The problem with using set_position() to move the spines into the middle of the plot area is that this removes them as elements of the plot's border. I'm looking for a way to restore the border lines using object-oriented operations on the Figure and Axes instances fig and ax, respectively.
Please note that I'm interested in manifestly object-oriented code only: operations on fig and ax. This constraint is a part of the question.
I won't accept an answer given in terms of plt or equivalent. I already know how to do that. I'll accept an answer demonstrating that it isn't possible to draw these border lines using only manifestly object-oriented code before I accept an answer using plt.

seaborn in jupyter notebook: why does sns.despine() work for lmplot but not regplot?

Jupyter notebook, using Python 3:
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
sns.despine()
then
snstest1 = sns.regplot(x="foo", y="bar", data=my_data)
shows a plot with the unwanted border box (i.e., sns.despine() doesn't seem to have affected it).
but:
snstest2 = sns.lmplot(x="foo", y="bar", data=my_data)
shows a plot with the unwanted border box correctly removed.
The only documentation I can find that seems to bear directly on this is the following, from the api docs for regplot:
Understanding the difference between regplot() and lmplot() can be a
bit tricky. In fact, they are closely related, as lmplot() uses
regplot() internally and takes most of its parameters. However,
regplot() is an axes-level function, so it draws directly onto an axes
(either the currently active axes or the one provided by the ax
parameter), while lmplot() is a figure-level function and creates its
own figure, which is managed through a FacetGrid. This has a few
consequences, namely that regplot() can happily coexist in a figure
with other kinds of plots and will follow the global matplotlib color
cycle. In contrast, lmplot() needs to occupy an entire figure, and the
size and color cycle are controlled through function parameters,
ignoring the global defaults.
But I don't fully understand the difference between a "figure" and an "axis." The best guess I can make without knowing the underlying model here is that when these weird global-state-mutating functions built into Seaborn, like despine and (?) set_palette and such, are active, only "figures," not "axes," check that state before rendering? But if that's so, how would I get something that generates an "axis" to plot in accordance with what I've requested?
In short: Call sns.despine after your plotting function.
The longer version:
lmplot creates its own figure. But it does not need despine. It will do it automatically, even without calling sns.despine.
import matplotlib.pyplot as plt
import seaborn as sns
tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", data=tips)
plt.show()
This is the reason the code from the question actually seems to work.
However, what is really happening is that if you call sns.despine before any figure is created, it will act on a newly created figure. The code from the question is hence creating two figures. One, which is empty, but also is "despined" and then one which is the lmplot figure and which is "despined" because every lmplot is despined by default.
A regplot is instead created in an axes of a matplotlib figure. If no figure or axes is provided, it will create a new one. This means that sns.despine needs to know which axes to despine. If you call it before anything else, there will again be two figures: One, which is empty, but also is "despined" and then one which is the regplot figure. This figures axes are not "despined", because noone told them so.
So the idea is of course to call sns.despine after creating the plot. You may specify which figure or axes to despine as argument (sns.despine(ax=ax))
import matplotlib.pyplot as plt
import seaborn as sns
tips = sns.load_dataset("tips")
ax = sns.regplot(x="total_bill", y="tip", data=tips)
sns.despine(ax=ax)
plt.show()
but if you only have a single subplot that wouldn't even be necessary. Hence
tips = sns.load_dataset("tips")
sns.regplot(x="total_bill", y="tip", data=tips)
sns.despine()
will work equally well and produce

multiple graph (not subplot) using python and matplotlib

I would like to plot two or more graphs at once using python and matplotlib. I do not want to use subplot since it is actually two or more plots on the same drawing paper.
Is there any way to do it?
You can use multiple figures and plot some data in each of them. The easiest way of doing so is to call plt.figure() and use the pyplot statemachine.
import matplotlib.pyplot as plt
plt.figure() # creates a figure
plt.plot([1,2,3])
plt.figure() # creates a new figure
plt.plot([3,2,1])
plt.show() # opens a window for each of the figures
If for whatever reason after creating a second figure you want to plot to the first one, you need to 'activate' it via
plt.figure(1)
plt.plot([2,3,1]) # this is plotted to the first figure.
(Figure numbers start at 1)

How to increase yaxis on seaborn stripplot

I am trying to increase the number of y-ticks for a stripplot.
My code is:
g = sns.stripplot(data=flightdelays,x="delay", y="schedtime", jitter=True, size=10)
I understand that I cannot alter the y-axis using the available commands within stripplot.
The y-axis is the scheduled time in 24-hour form. Is someone able to show me how to set the yticks to every 100 i.e. every hour?
The seaborn plot returns an instance of a matplotlib axes object, which means that any matplotlib axes function can be called. So the solution here is:
g.set_ylim([min,max])

Categories