根据y值的分条

问题描述 投票:0回答:2

我有一个带有两个变量的数据集:

  • [district:瓦特/ 26级(A,B,C,D等)]
  • type:“ x”,“ o”(因数)

现在我想绘制一个堆积的条形图:每年一个条形图。

ggplot(aes(x = district, fill=type), data=dat) + geom_bar()

我的问题是,小节应该按升序排列(在每个分区的总数中)。像这样:

  |
  |  x
  |  x
  |  x  x
n |  o  x  x
  |  o  o  o
  |  o  o  o  x
  |  o  o  o  o 
  _______________
     A  C  G  B …

有人知道该怎么做吗?

r ggplot2 geom-bar
2个回答
1
投票

这里是您的数据的代表:

district <- sample(LETTERS, 1000, replace = TRUE)
xo <- c("x","o")
type <- sample(xo, 1000, replace = TRUE)

这里是您的df。您需要创建一个count列,您可以根据该列对各地区进行排序。

df <- as.data.frame(cbind(district, type)) %>%
  group_by(district) %>%
  mutate(count = n())

aes参数中,您可以通过递减计数来指定reorder区:

ggplot(df, aes(x = reorder(district, -count), fill=type)) +
  geom_bar()

1
投票

如果您的data.frame纯粹是两级的列,请执行:

library(ggplot2)
set.seed(111)
df = data.frame(district=sample(LETTERS[1:4],100,replace=TRUE),
type=sample(c("x","o"),100,replace=TRUE))

head(df)

  district type
1        B    x
2        C    o
3        D    x
4        C    x
5        C    x
6        A    x

ggplot(df,aes(x=reorder(district,district,function(i)-length(i)),fill=type)) + geom_bar()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.