【问题标题】:Plotting in sorted order using Plotnine使用 Plotnine 按排序顺序绘图
【发布时间】:2020-06-22 04:09:37
【问题描述】:

我有一个我正在尝试绘制的数据框。我希望数据点在我的图中沿 x 轴按排序顺序显示。我曾尝试在将数据框传递给 ggplot 之前对其进行排序,但是我的订单被忽略了。我的数据如下,我要对'value'属性进行排序。

       var1     var2  value     direction
0      PM25     PBAR  0.012001          1
1      PM25  DELTA_T  0.091262          1
2      PM25       RH  0.105857          1
3      PM25      WDV  0.119452          0
4      PM25     T10M  0.119506          0
5      PM25      T2M  0.129869          0
6      PM25     SRAD  0.134718          0
7      PM25      WSA  0.169000          0
8      PM25      WSM  0.174202          0
9      PM25      WSV  0.181596          0
10     PM25      SGT  0.263590          1

这是我的代码目前的样子:

tix = np.linspace(0,.3,10)
corr = corr.sort_values(by='value').reset_index(drop = True)
p = ggplot(data = corr, mapping = aes(x='var2', y='value')) +\
  geom_point(mapping = aes(fill = 'direction')) + ylab('Correlation') + ggtitle('Correlation to PM25') +\
  theme_classic() +  scale_y_continuous(breaks = tix, limits = [0, .3])

print(p)

这会产生以下情节:

1

【问题讨论】:

  • 默认情况下,ggplot2 会将沿 x 轴的任何文本元素视为因子变量,并按字母顺序设置级别。要获得您想要的行为,您需要使您的 Variable 值成为提供的顺序中的一个因素。然后尝试重新创建情节。
  • 但是当我点击提交时,我没有意识到这是一个 Python 实现。上面的评论是你在 R 中需要做的。它可能适用也可能不适用。

标签: python pandas ggplot2 plotnine


【解决方案1】:

你可以通过两种方式做到这一点

  1. 确保映射到 x 轴的变量是分类变量,并且类别排序正确。下面我使用 pd.unique 按出现顺序返回值的事实。
corr.sort_values(by='value').reset_index(drop = True)
corr['var2'] = pd.Categorical(corr.var2, categories=pd.unique(corr.var2))
...
  1. Plotnine 有一个内部函数 reorder(在 v0.7.0 中引入),您可以在 aes() 调用中使用它来根据另一个变量的值更改一个变量的值的顺序。请参阅页面底部的 reorder 文档。
# no need to sort values
p = ggplot(data = corr, mapping = aes(x='reorder(var2, value)', y='value')) +\
...

【讨论】:

  • 谢谢!第一次尝试使用“重新排序”效果很好。
【解决方案2】:

我无法让reorder() 工作,但我能够使用scale_x_discrete() 来控制订单。见https://stackoverflow.com/a/63578556/7685

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    相关资源
    最近更新 更多