简体   繁体   English

如何使用ggplot2在R中重新排列此条形图?

[英]How do I reorder this bar plot in R using ggplot2?

I am trying to create a bar plot with two layers, one ordered by counts, and the other one a running total of the counts. 我正在尝试创建一个具有两层的条形图,一层按计数排序,另一层按计数累计。 This is where I am at the moment: 这是我目前的位置:

ggplot(data = df %>% group_by(variable_int) %>% summarise(n = n()) , 
   aes(x = as.factor(variable_int), y = n)) + 
   geom_col() +
   geom_col(aes(y = cumsum(n)), alpha = 0.3)

The variable is categorical but the levels are integers (0-20), hence why I've used as.factor(). 该变量是分类变量,但级别是整数(0-20),因此为什么我使用as.factor()。

What I'd like to do is order the bar plot in an ascending fashion by counts for the first layer ( geom_col() ), with a transparent running total (second) layer appearing in the background of the plot. 我想做的是按照第一层的计数( geom_col() )以递增的方式对geom_col() ,并在图的背景中出现一个透明的运行总计(第二层)。 What I've got at the moment though is the running total layer in ascending order and the other layer ordered in terms of its categorical level (ie 0-20), not in terms of its counts, so it appears unordered. 不过,目前我得到的是按顺序升序运行的总层,而另一层则按其分类级别(即0-20)而不是按其计数来排序,因此它看起来是无序的。

I've tried using x = reorder(as.factor(variable_int),n) but this doesn't seem to work. 我尝试使用x = reorder(as.factor(variable_int),n)但这似乎不起作用。

Any help would be much appreciated! 任何帮助将非常感激! Thanks! 谢谢!

try this, the trick is to set the levels of variable_int factor. 试试这个,诀窍是设置variable_int因子的级别。

library(tidyverse)
df <- data.frame(variable_int = sample(1:20, 30,replace = T))

gg.data <- 
  df %>% 
  group_by(variable_int) %>% 
  summarise(n = n()) %>%
  arrange(n) %>%
  ungroup() %>%
  mutate(variable_int=factor(variable_int, levels = variable_int))

ggplot(data = gg.data , 
   aes(x = variable_int, y = n)) + 
   geom_col() +
   geom_col(aes(y = cumsum(n)), alpha = 0.3)

Created on 2018-07-26 by the reprex package (v0.2.0.9000). reprex软件包 (v0.2.0.9000)创建于2018-07-26。

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

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