How to increase yaxis on seaborn stripplot - python

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])

Related

How to adjust subplots borders in matplotlib automatically?

When plotting multiple plots using plt.subplots, most of the time the spacing between subplots is not ideal so the the xtick labels of the top plot would overlap with the title of the bottom plots. There is a way to fix this manually by calling say plt.subplots_adjust(hspace=0.5) and changing the parameters interactively to obtain a decent looking plot. Is there a way to calculate the subplot_adjust parameter automatically? Meaning finding the minimum hspace and wspace so that there is not overlap between texts of the plots.
You can use tight_layout https://matplotlib.org/stable/tutorials/intermediate/tight_layout_guide.html or constrained_layout https://matplotlib.org/stable/tutorials/intermediate/constrainedlayout_guide.html
I'm pretty certain that the closest your going to find to an inbuilt calculation method is:
plt.tight_layout()
or
figure.Figure.tight_layout() #if you are using the object version of the code

How can I plot figures from pandas series in different windows?

I am new in python and I create pandas series in a for-loop. Each time I want to plot the series in a figure. I use ax = series.plot(title = str(i)+'.jpg') but all figures are plotted in same window. How can I plot them in different windows?
If you are using matplotlib, use
plt.figure()
for every new figure you want to plot.
You then show all figures with
plt.show()
also, you should check out what subplots does.

Clearing the Matplotlib plot without clearing slider

I'm currently creating an application where I need to update matplotlib graphs. I'm stuck at following step.
I have a scatter plot and slider in the same figure. Upon changing the slider value, I need to clear the scatter plot without clearing the slider. Following is the code I implemented, but it does not clear the plot.
The .clf() function removes both the slider and scatter plot. Is there a way I could remove only the plot without impacting the slider?
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
X1=np.arange(10)
Y1=np.arange(10)
Z1=np.arange(10)
fig,ax=plt.subplots()
ax=plt.scatter(X1,Y1,Z1)
axSlider1=plt.axes([0.3,0.9,0.3,0.05])
Slder2=Slider(ax=axSlider1,label='Slider',valmin=1,valmax=4,valinit=2)
plt.show()
# Function to clear the scatter plot without effecting slider.
def val_update(val):
plt.cla()
Slder2.on_changed(val_update)
fig,ax=plt.subplots()
Assigned the Axes object to ax - then
ax=plt.scatter(X1,Y1,Z1)
assigns a PathCollection object to ax. So val_update is tying to act on the wrong thing.
This seems to solve the issue you asked about.
X1=np.arange(10)
Y1=np.arange(10)
Z1=np.arange(10)
fig,ax=plt.subplots()
path=plt.scatter(X1,Y1,Z1)
axSlider1=plt.axes([0.3,0.9,0.3,0.05])
Slder2=Slider(ax=axSlider1,label='Slider',valmin=1,valmax=4,valinit=2)
# Function to clear the scatter plot without effecting slider.
def val_update(val):
print(val)
ax.clear()
Slder2.on_changed(val_update)
plt.show()
The Matplotlib Gallery is a good resource you can browse through it looking for features you want and see how they were made. - Like this slider demo
If you think you will be using matplotlib in the future I would recommend working your way through the Introductory tutorials and at least the Artists tutorial

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

Empty python plot

I'm running a script remotely on a cluster to generate a scatter plot. I wish to save the plot, but I don't want the plot to be display or a window to come up (as when you execute plt.show() ).
My saved plots are always empty. This is the code that I'm using (below). Any tips would be very helpful. Thanks!
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlim([-1,maxX+1])
ax.set_ylim([0,maxY+1])
ax.set_xlabel('Comparison number (n)', fontsize=18, fontweight='bold')
ax.set_ylabel('Normalized cross correlation score', fontsize=18, fontweight='bold')
ax.scatter(xaxis,yaxis)
plt.savefig('testfig.png')
In order to use avoid showing plot windows (i.e. to do off-screen rendering) you probably want to use a different matplotlib backend.
Before any matplotlib import statements, add
import matplotlib
matplotlib.use('Agg')
and subsequent calls to matplotlib will not show any plot windows.
If your plot file shows an empty axis, then the problem lies in the plotting arguments as calling plot with empty arguments creates an empty axis.

Categories