繁体   English   中英

ggplot2中的水平条形图

[英]Horizontal Barplot in ggplot2

我正在研究ggplot2的水平点图(?),这让我开始考虑尝试创建水平条形图。 但是,我发现能够做到这一点有一些限制。

这是我的数据:

df <- data.frame(Seller=c("Ad","Rt","Ra","Mo","Ao","Do"), 
                Avg_Cost=c(5.30,3.72,2.91,2.64,1.17,1.10), Num=c(6:1))
df
str(df)

最初,我使用以下代码生成了一个点图:

require(ggplot2)
ggplot(df, aes(x=Avg_Cost, y=reorder(Seller,Num))) + 
    geom_point(colour="black",fill="lightgreen") + 
    opts(title="Avg Cost") +
    ylab("Region") + xlab("") + ylab("") + xlim(c(0,7)) +
    opts(plot.title = theme_text(face = "bold", size=15)) +
    opts(axis.text.y = theme_text(family = "sans", face = "bold", size = 12)) +
    opts(axis.text.x = theme_text(family = "sans", face = "bold", size = 12))

但是,我现在正在尝试创建一个水平条形图并发现我无法这样做。 我试过coord_flip()也没有帮助。

ggplot(df, aes(x=Avg_Cost, y=reorder(Seller,Num))) + 
    geom_bar(colour="black",fill="lightgreen") + 
    opts(title="Avg Cost") +
    ylab("Region") + xlab("") + ylab("") + xlim(c(0,7)) +
    opts(plot.title = theme_text(face = "bold", size=15)) +
    opts(axis.text.y = theme_text(family = "sans", face = "bold", size = 12)) +
    opts(axis.text.x = theme_text(family = "sans", face = "bold", size = 12)) 

任何人都可以就如何在ggplot2生成水平条形图提供一些帮助吗?

ggplot(df, aes(x=reorder(Seller, Num), y=Avg_Cost)) +
  geom_bar(stat='identity') +
  coord_flip()

没有stat='identity' ggplot 想要将您的数据聚合为计数。

ggplot2版本 3.3.0(2020 年 3 月)开始,该方向已从美学映射中扣除。 因此我们可以将@Justin 和@ungatoverde 的代码简化为

library(ggplot2)
ggplot(df,
       aes(x = Avg_Cost,
           y = reorder(Seller, Num)
           )
       ) +
  geom_col()

在此处输入图像描述

参考: https : //www.tidyverse.org/blog/2020/03/ggplot2-3-3-0/#bi-directional-geoms-and-stats

ggplot(df, aes(x=reorder(Seller, Num), y=Avg_Cost)) +
  geom_col()

这可能是另一种选择

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM