Seaborn scatter plot increase the thickness of vline marker - python

I am generating a KDE plot and adding the data points as a scatter plot as well. I am using the vline marker "|" for this scatterplot. How can I increase the thickness of this marker. Increasing s=200 to s=1000 increases the height as well. Is there a way to change the thickness without changing the height?
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
numberList = np.random.rand(20)
ax = sns.kdeplot(numberList)
ax = sns.scatterplot(x=numberList, y=0.1, marker='|', s=200)
plt.show()

I found a solution. Adding a parameter linewidth=3 helped.
ax = sns.scatterplot(x=numberList, y=0.1, marker="|", s=200, linewidth=3)

Related

fixing the y scale in python matplotlib

I want to draw multiple bar plots with the same y-scale, and so I need the y-scale to be consistent.
For this, I tried using ylim() after yscale()
plt.yscale("log")
plt.ylim(top=2000)
plt.show()
However, python keeps autoscaling the intermittent values depending on my data.
Is there a way to fix this?
overlayed graphs
import numpy as np
import matplotlib.pyplot as plt
xaxis = np.arange(10)
yaxis = np.random.rand(10)*100
fig = plt.subplots(figsize =(10, 7))
plt.bar(xaxis, yaxis, width=0.8, align='center', color='y')
# show graph
plt.yscale("log")
plt.ylim(top=2000)
plt.show()
You can set the y-axis tick labels manually. See yticks for an example. In your case, you will have to do this for each plot to have consistent axes.

Colorbar for sns.jointplot "kde"-style on the side

I'm trying to plot a colorbar next to my density plot with marginal axes.
It does plot the colorbar, but unfortunately not on the side.
That's what a tried so far:
sns.jointplot(x,y, data=df3, kind="kde", color="skyblue", legend=True, cbar=True,
xlim=[-10,40], ylim=[900,1040])
It looks like this:
I also tried this:
from matplotlib import pyplot as plt
import seaborn as sns
import numpy as np
kdeplot = sns.jointplot(x=tumg, y=pumg, kind="kde")
plt.subplots_adjust(left=0.2, right=0.8, top=0.8, bottom=0.2)
cbar_ax = kdeplot.fig.add_axes([.85, .25, .05, .4])
plt.colorbar(cax=cbar_ax)
plt.show()
But with the second option I'm getting a runtime error:
No mappable was found to use for colorbar creation.
First define a mappable such as an image (with imshow) or a contour set (with contourf).
Does anyone have an idea how to solve the problem?
There only seems to be information for a colorbar when effectively creating the colorbar.
So, an idea is to combine both approaches: add a colorbar via kdeplot, and then move it to the desired location. This will leave the main joint plot with insufficient width, so its width also should be adapted:
from matplotlib import pyplot as plt
import seaborn as sns
import numpy as np
# create some dummy data: gaussian multivariate with 10 centers with each 1000 points
tumg = np.random.normal(np.tile(np.random.uniform(10, 20, 10), 1000), 2)
pumg = np.random.normal(np.tile(np.random.uniform(10, 20, 10), 1000), 2)
kdeplot = sns.jointplot(x=tumg, y=pumg, kind="kde", cbar=True)
plt.subplots_adjust(left=0.1, right=0.8, top=0.9, bottom=0.1)
# get the current positions of the joint ax and the ax for the marginal x
pos_joint_ax = kdeplot.ax_joint.get_position()
pos_marg_x_ax = kdeplot.ax_marg_x.get_position()
# reposition the joint ax so it has the same width as the marginal x ax
kdeplot.ax_joint.set_position([pos_joint_ax.x0, pos_joint_ax.y0, pos_marg_x_ax.width, pos_joint_ax.height])
# reposition the colorbar using new x positions and y positions of the joint ax
kdeplot.fig.axes[-1].set_position([.83, pos_joint_ax.y0, .07, pos_joint_ax.height])
plt.show()

Facetgrid: how to space the xticks

I have several histograms that I need to plot with seaborn / facetgrid. They each have their own different x/y axis scales. I need to control the space between the ticks, so as to make it readable (right now they are all overlapping with each other). It won't help to force set the ticks, as each histogram has it's own scale. Here is my current code:
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
sns.set(style="ticks")
g = sns.FacetGrid(test, col="someCol", sharex=False, sharey=False)
g.map(plt.hist, "someVal")
And this is what my histograms look like so far:
You can rotate the ticks using this command :
ax.tick_params(axis='x', rotation = 90, labelsize = 20)

Add an x-axis at 0 to a pyplot histogram with negative bars

In the histogram produced with the following code, there's no x axis at the zero level
import matplotlib.pyplot as plt
plt.bar(left=[0,4,5],height=[-100,10,110],color=['red','green','green'],width=0.1)
plt.show()
How to put it there?
I tend to use spines to get the x-axis centered:
import matplotlib.pyplot as plt
fig = plt.figure(facecolor='white')
ax = fig.add_subplot(1,1,1)
ax.bar(left=[0,4,5],height=[-100,10,110],color=['red','green','green'],width=0.1)
ax.grid(b=True)
ax.spines['left'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('zero')
ax.spines['top'].set_color('none')
plt.show()
Which will produce the next plot:
By default matplotlib does not consider the y=0 line important. You can turn on the grid by a call such as plt.grid().
An alternative used often in the matplotlib.pylab docs is to set a horizontal line at 0. This is done by
plt.axhline(0, color='black', lw=2)

how to make rug plot in matplotlib

Im making a density plot with matplotlib and I would also like to get rug plot under it. good example to make density plot is here How to create a density plot in matplotlib?
but I couldn't find any good example for rug plot. in R it can be done easly by rug(data).
You can plot markers at each datapoint.
from scipy import stats
import numpy as np
import matplotlib.pyplot as plt
sample = np.hstack((np.random.randn(30), np.random.randn(20)+5))
density = stats.kde.gaussian_kde(sample)
fig, ax = plt.subplots(figsize=(8,4))
x = np.arange(-6,12,0.1)
ax.plot(x, density(x))
ax.plot(sample, [0.01]*len(sample), '|', color='k')
You can find an example here!
ax = fig.add_subplot(111)
ax.plot(x1, np.zeros(x1.shape), 'b+', ms=20) # rug plot
x_eval = np.linspace(-10, 10, num=200)
ax.plot(x_eval, kde1(x_eval), 'k-', label="Scott's Rule")
ax.plot(x_eval, kde1(x_eval), 'r-', label="Silverman's Rule")
Seems to be the core of it!
You can also use Seaborn.distplot, which wraps histogram, KDE and rugs altogether. Figures made by Seaborn are also prettier by default.
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sample = np.hstack((np.random.randn(30), np.random.randn(20)+5))
fig, ax = plt.subplots(figsize=(8,4))
sns.distplot(sample, rug=True, hist=False, rug_kws={"color": "g"},
kde_kws={"color": "k", "lw": 3})
plt.show()
Here's the answer for people just looking for a rugplot to use on a matplotlib axis: you can use a seaborn function.
import seaborn as sns
sns.rugplot(xdata, height=0.025, axis=ax, color='k')
This looks much nicer than a pure-matplotlib kludge because the rug is aligned to (flush with) the x-axis.

Categories