如何使用带有结构数据框的 ggplot2 创建条形图?

要使用带有结构数据的 ggplot2 创建条形图,我们需要将 geom_bar 函数的 stat 参数设置为 identity。这与常规数据框相同。

例如,如果我们有一个名为 df 的结构化数据框,其中包含用于类别的列 X 和表示频率的数字列 Y,那么我们可以使用以下给定命令绘制此数据的条形图 -

ggplot(df,aes(X,Y))+geom_bar(stat="identity")

示例

以下代码段创建了一个示例数据框 -

df<-structure(list(X=c("A","B","C"),Count=c(10,18,9)),.Names=c("X","Count"),row.names=c(NA, -3L),class="data.frame")
df
输出结果

创建以下数据框 -

   X  Count
1  A  10
2  B  18
3  C   9

要加载 ggplot2 包并为 df 中的数据创建条形图,请将以下代码添加到上述代码段 -

library(ggplot2)
ggplot(df,aes(x=X,y=Count))+geom_bar()
输出结果

如果您将上述所有片段作为单个程序执行,它会生成以下输出 -

Error: stat_count() can only have an x or y aesthetic.
Run `rlang::last_error()` to see where the error occurred.

加载 ggplot2 包并创建条形图的正确代码如下 -

ggplot(df,aes(x=X,y=Count))+geom_bar(stat="identity")
输出结果

如果您将上述所有片段作为单个程序执行,它会生成以下输出 -

猜你喜欢