条形图,y 轴计数,x 轴年份,2 个颜色组

Posted

技术标签:

【中文标题】条形图,y 轴计数,x 轴年份,2 个颜色组【英文标题】:Bar plot with count on yaxis and year on x axis with 2 color groups 【发布时间】:2022-01-14 07:00:32 【问题描述】:

这对于了解 ggplot2 的人来说可能很容易,所以也许有人可以为我做一个快速的情节:) 这是我想要获得的示例数据和描述。

    Year <- c(1991, 1992,1995,1991,1992,1992)
    Type <- c("B", "B", "D", "D", "D", "D")
    df <- data.frame(Year, Type)
    df
  Year Type
1 1991    B
2 1992    B
3 1995    D
4 1991    D
5 1992    D
6 1992    D

我想用 ggplot2 创建一个条形图,在 X 轴上我有单独的年份,在 Y 轴上的年数就像有 3 1992 年一样,并将 B 和 D 的颜色分开。我想我不知何故必须数数。同一年在一个组中,然后将其添加到数据框中,但我不知道该怎么做。

【问题讨论】:

到目前为止你的尝试是什么? @ArtūrsKatamadze 比不要忘记太好了 当有人回答我的问题时我该怎么办? ***.com/help/someone-answers 这能回答你的问题吗? Plotting a stacked bar plot? 【参考方案1】:
df1 <-df %>% 
  count(Year, Type) %>%
  mutate(Freq = n/sum(n))

ggplot(df1, aes(x=Year, y=Freq, fill=Type))+  
  geom_bar(stat="identity") + 
  geom_text(aes(label=scales::percent(Freq)), position = position_stack(vjust = .5))+
  theme_classic() + 
  labs(title = "", x = "Year", y = "%", fill="Type")+  
  scale_fill_discrete(name= "Type")

或者你可以使用count(Year, Type)

df1 <-df %>% 
  count(Year, Type) 


ggplot(df1, aes(x=Year, y=n, fill=Type))+  
  geom_bar(stat="identity") + 
  geom_text(aes(label=n), position = position_stack(vjust = .5))+
  theme_classic() + 
  labs(title = "", x = "Year", y = "Count", fill="Type")+  
  scale_fill_discrete(name= "Type")

【讨论】:

谢谢,这正是我要找的! 嘿,我还有一个问题。是否可以将有值的年份加粗(1991、1992、1995)

以上是关于条形图,y 轴计数,x 轴年份,2 个颜色组的主要内容,如果未能解决你的问题,请参考以下文章