TheLaama
TheLaama

Reputation: 307

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

Upvotes: 9

Views: 12118

Answers (4)

CPBL
CPBL

Reputation: 4030

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.

Upvotes: 0

Zichen Wang
Zichen Wang

Reputation: 1374

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

enter image description here

Upvotes: 4

Steve Barnes
Steve Barnes

Reputation: 28370

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!

Upvotes: 4

Rutger Kassies
Rutger Kassies

Reputation: 64443

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

enter image description here

Upvotes: 15

Related Questions