【问题标题】:Set axis offset dynamically on seaborn.despine()在 seaborn.despine() 上动态设置轴偏移
【发布时间】:2020-07-19 10:08:28
【问题描述】:

我想动态计算 seaborn.despine() 的轴偏移量。它应该坚持我的 matplotlib 轴的 0 值。但不知何故,我似乎有错误的计算概念。

由于我需要以点为单位设置 seaborn 的偏移量,因此我尝试计算图像大小,并将其设置为与 x 轴成比例,但从下面的小代码示例中可以看出,这不起作用想要的。

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

# Define and use a simple function to label the plot in axes coordinates
def label(x, color, label):
    ax = plt.gca()
    ax.text(0, .2, label, fontweight="bold", color=color,
            ha="left", va="center", transform=ax.transAxes)

# Create sample data
rs = np.random.RandomState(1979)
x = rs.randn(500)
g = np.tile(list("ABCDEFGHIJ"), 50)
df = pd.DataFrame(dict(x=x, g=g))

# Plot
sns.set(style="white", rc={"axes.facecolor": (0, 0, 0, 0)})

pal = sns.color_palette("hls")
# Initialize the FacetGrid object
g = sns.FacetGrid(df, row="g", hue="g", aspect=20, height=0.7, palette=pal)

# Draw the densities in a few steps
g.map(sns.kdeplot, "x", clip_on=False, shade=True, alpha=0.7, lw=2, bw='scott')
g.map(sns.kdeplot, "x", clip_on=False, color="k", lw=1, bw='scott')

g.map(label, "x")

# Set the subplots to overlap
g.fig.subplots_adjust(hspace=-.25)


# calculate offset for left axis
ax = g.axes[0]
ax_size = abs(ax[0].get_xlim()[0]) + ax[0].get_xlim()[1]
fig = g.fig
size = fig.get_size_inches()*fig.dpi
fig_size = size[0]
off = fig_size * ax[0].get_xlim()[0] / ax_size

# Remove axes details that don't play well with overlap
g.set_titles("")
g.set(yticks=[])
g.despine(bottom=False, left=False, offset={'left':off}); # set offset

情节如下所示:

可以看出,轴偏离零值。 有谁知道如何解决这个问题?

提前致谢,

Exi

【问题讨论】:

    标签: python pandas numpy matplotlib seaborn


    【解决方案1】:

    不错的 MWE。在matplotlib中有一些issueswith如何处理点中的规范,我认为问题可能与它们有关。暂时尽量避免任何以点为单位的规范。

    Seaborn 的“绝望”强制使用点数;然而,我们可以回退到相应的 matplotlib 函数,它更灵活,甚至有一个方便的简写,可以将脊椎集中在数据源上。

    for ax in g.axes.ravel():
        ax.spines['left'].set_position('zero')
    

    另外,我建议您阅读 transformations in matplotlib,然后您不需要像计算 off 时那样手动计算它们。

    【讨论】:

      猜你喜欢
      • 2018-02-22
      • 1970-01-01
      • 2016-07-07
      • 2019-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多