首页 > 解决方案 > Plotnine - 在同一图表中添加垂直线和直方图

问题描述

我试图弄清楚如何在 python 中做到这一点,因为我对它比 R 有点新。

import plotnine as p9
import pandas as pd
import numpy as np

###load the data here...
dataset=pd.read_csv('https://gist.githubusercontent.com/curran/a08a1080b88344b0c8a7/raw/d546eaee765268bf2f487608c537c05e22e4b221/iris.csv')

什么不起作用的例子......不知道我做错了什么......

p9.ggplot(dataset, p9.aes(x='sepal_width'))+p9.geom_density()+p9.geom_vline( p9.aes(xintercept='sepal_length.mean()', color='species'))

为什么颜色不起作用?我想要一个具有适当颜色的垂直线

如果我可以覆盖直方图也很棒。

标签: pythonplotnine

解决方案


您必须单独进行数据操作。如果计算是在stat. 对于您的情况,计算是通过映射完成的,即xintercept='sepal_length.mean()'映射xinterceptsepal_length平均值,它不关心color='species',所以xintercept是全局平均值!

from plotnine import *
from plydata import *

df = (
    dataset
    >> group_by('species')
    >> summarise(sl_mean='mean(sepal_length)')
)

(ggplot(dataset, aes(x='sepal_width'))
 + geom_density()
 + geom_vline(df, aes(xintercept='sl_mean', color='species'))
)

结果图

添加直方图

(ggplot(dataset, aes(x='sepal_width'))
 + geom_histogram(aes(y='stat(density)'), alpha=.2)
 + geom_density()
 + geom_vline(df, aes(xintercept='sl_mean', color='species'))
)

在此处输入图像描述


推荐阅读