简体   繁体   English

Matplotlib/Seaborn:如何在 x 轴的顶部边缘绘制 rugplot?

[英]Matplotlib/Seaborn: how to plot a rugplot on the top edge of x-axis?

Suppose I draw a plot using the code below.假设我使用下面的代码绘制了一个图。 How to plot the rug part on the top edge of x-axis?如何在 x 轴的上边缘绘制地毯部分?

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

sns.distplot(np.random.normal(0, 0.1, 100), rug=True, hist=False)
plt.show()

在此处输入图片说明

Rugs are just thin lines at the data points.地毯只是数据点处的细线。 Yo can think of them as thin bars.你可以把它们想象成细条。 That being said, you can have a following work around: Plot distplot without rugs and then create a twin x-axis and plot a bar chart with thin bars .话虽如此,您可以进行以下工作:绘制没有地毯的distplot ,然后创建一个双 x 轴并绘制一个带有细条的条形图 Following is a working answer:以下是一个有效的答案:

import numpy as np; np.random.seed(21)
import matplotlib.pyplot as plt
import seaborn as sns

fig, ax = plt.subplots()

data = np.random.normal(0, 0.1, 100)
sns.distplot(data, rug=False, hist=False, ax=ax)

ax1 = ax.twinx()
ax1.bar(data, height=ax.get_ylim()[1]/10, width=0.001)
ax1.set_ylim(ax.get_ylim())
ax1.invert_yaxis()
ax1.set_yticks([])
plt.show()

在此处输入图片说明

The seaborn.rugplot creates a LineCollection with the length of the lines being defined in axes coordinates. seaborn.rugplot创建一个LineCollection ,其中线的长度在轴坐标中定义。 Those are always the same, such that the plot does not change if you invert the axes.这些总是相同的,因此如果反转轴,图不会改变。

You can create your own LineCollection from the data though.不过,您可以根据数据创建自己的LineCollection The advantage compared to using bar s is that the linewidth is in points and therefore no lines will be lost independend of the data range.与使用bar相比的优点是线宽以点为单位,因此不会丢失独立于数据范围的线。

import numpy as np; np.random.seed(42)
import matplotlib.pyplot as plt
import seaborn as sns

def upper_rugplot(data, height=.05, ax=None, **kwargs):
    from matplotlib.collections import LineCollection
    ax = ax or plt.gca()
    kwargs.setdefault("linewidth", 1)
    segs = np.stack((np.c_[data, data],
                     np.c_[np.ones_like(data), np.ones_like(data)-height]),
                    axis=-1)
    lc = LineCollection(segs, transform=ax.get_xaxis_transform(), **kwargs)
    ax.add_collection(lc)

fig, ax = plt.subplots()

data = np.random.normal(0, 0.1, 100)
sns.distplot(data, rug=False, hist=False, ax=ax)

upper_rugplot(data, ax=ax)

plt.show()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM