【问题标题】:plotnine shows discrete values in the wrong placeplotnine 在错误的地方显示离散值
【发布时间】:2021-12-10 00:54:18
【问题描述】:

每当列具有特定(离散)值时,我正在尝试制作一个在 x 轴上显示时间并在 y 轴上显示点的图形。

以下是一些示例数据:

dat = pd.DataFrame({
    'time': [0, 15, 30],
    'A': [np.nan, np.nan, 'A'],
    'B': ['B', 'B', np.nan],
})

现在,每当“A”列显示字母“A”时,我都会尝试在“A”列中显示一个点。我试过这个:

(gg.ggplot(dat, gg.aes('time', 'A'))
  + gg.geom_point()
  + gg.scale_y_discrete(name='', limits=list('A'))
)

但是什么也没显示: link to figure

然后,我更改了绘图的 y 限制:

(gg.ggplot(dat, gg.aes('time'))
  + gg.geom_point(gg.aes(y='A'))
  + gg.scale_y_discrete(name='', limits=list('ABCD'))
)

现在,我想要的点出现了:“A”列在 30 时显示值“A”,确实,那里有一个点。但非常奇怪的是,该图还在“D”列中显示了两个点: link to figure

我玩了一下限制和列名,只要限制包含少于 4 个值,就根本不会出现点;之后,我想要的点会出现,但 NaN 值也会被绘制在限制中最后一个字母的列中。

有人知道这里发生了什么吗?你能帮我做这个图吗?

【问题讨论】:

    标签: python plotnine


    【解决方案1】:

    您需要做的第一件事是重塑数据框,以便将变量和值堆叠起来,然后删除缺失值。

    import pandas as pd
    import numpy as np
    from plotnine import *
    
    df = pd.DataFrame({
        'time': [0, 15, 30],
        'A': [np.nan, np.nan, 'A'],
        'B': ['B', 'B', np.nan],
    })
    
    df = pd.melt(df, id_vars=['time'], value_vars=['A', 'B'])
    df.dropna(inplace=True)
    
    p = (ggplot(df, aes(x='time', y='value'))
      + theme_classic()
      + geom_point()
      + labs(y=None)
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-25
      • 1970-01-01
      • 2018-08-01
      • 2021-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多