如何在Python ggplot中创建柱状图?

11 投票
1 回答
16706 浏览
提问于 2025-04-17 23:35

我正在使用yhat的ggplot库。我有一个这样的pandas数据框:

   degree  observed  percent observed  expected  percent expected
0       0         0               0.0         0          0.044551
1       1         1               0.1         1          0.138604
2       2         3               0.3         2          0.215607
3       3         4               0.4         2          0.223592
4       4         1               0.1         2          0.173905
5       5         1               0.1         1          0.108208

目前,我正在做以下操作(这里的df是上面提到的数据框):

def chartObservedExpected(graph):
    df = observedExpected(graph)
    return ggplot(aes(x='degree', y='percent observed'), data=df) + \
           geom_point() + \
           ylim(-0.015,1.015) + \
           xlim(-0.05,max(df['degree']) + 0.25) + \
           labs("Degree","Proportion of Total") + \
           ggtitle("Observed Node Degree Distribution")

chartObservedExpected(G)

这是我得到的结果:

scatter

但是,每当我尝试用geom_bar()代替geom_point()时,我得到的都是100%的柱状图。我试过直接用geom_bar(),也试过geom_bar(stat="percent observed"),但都没有效果。结果总是这样:

bar

我想要做的是模仿/重现以下效果:

attempt

有没有什么办法让柱状图部分正常工作(或者整个图表都正常)?

1 个回答

24

使用 weight,下面是一个例子:

from ggplot import *
import pandas as pd
df = pd.DataFrame({"x":[1,2,3,4], "y":[1,3,4,2]})
ggplot(aes(x="x", weight="y"), df) + geom_bar()

输出结果看起来像这样:

在这里输入图片描述

撰写回答