繁体   English   中英

带有 R 的 Geom_bar(初学者)

[英]Geom_bar with R (Beginner)

大家早上好,

根据我的两个部门,我处理我想以条形图的形式表示的数据。 我生成了一个看起来像这样的 dataframe:

> test = data.frame (type_transport = sample (c ("ON FOOT", "CAR", "TRANSPORT COMMON"), 5000, replace = T), type_route = sample (c ("N", "D", " A "," VC "), 5000, replace = T), department = sample (c (" department1"," department2"), 5000, replace = T), troncon = sample (x = 0: 17 , 5000, replace = T))

通过输入这个公式,我得到一个条形图:

> ggplot (test, aes (x = route_type, y = troncon_km, fill = department)) + geom_bar (stat = "identity")

https://zupimages.net/viewer.php?id=20/19/vt1s.png

现在,我想将这些条分成两半,以根据我的两个部门显示数据。 为此,我使用 position = "dodge":

> ggplot (test, aes (x = road_type, y = troncon_km, fill = department)) + geom_bar (stat = "identity", position = "dodge")

但有一个问题。 Y 比例与现实相比太小了(我们的 go 从第一张图上的几千到第二张图上的 15)。 我显然错过了什么......

https://zupimages.net/viewer.php?id=20/19/sbh5.png

我不明白。

谢谢你。

所有条形高度相等的原因是geom_bar(stat="identity")将为每个观察值 plot 一个条形(并且条形的高度将等于该观察值的值)。 由于两个部门中的每个类别都至少有 1 个观测值 17,因此所有条形都显示该值。

有几种前进的方法:

    1.
ggplot(test, aes(type_route, troncon_km, fill = department)) +
  stat_summary(geom = "bar", position = "dodge", fun.y = sum)

fun.y 参数可以是任何其他 function(例如均值或中值等)

2.

library("tidyverse")
total_km <- test %>%
    group_by(department, type_route) %>%
    summarise(total_km = sum(troncon_km)) 

ggplot(total_km, aes(type_route, total_km, fill = department)) +
    geom_bar(stat = "identity", position = "dodge")

同样,您可以根据自己的喜好更改 summarise summarise() ) 中的sum() function。

  1. 使用相同的数据框total_km ,使用geom_col只短一点

ggplot(total_km, aes(type_route, total_km, fill = department)) +
  geom_col(position = "dodge")

希望这可以帮助。

暂无
暂无

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

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