ggplot2用于带有两个相同刻度标签的条形图

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

我有一个数据集,如:

日期值标签

2016/01 2 A

2016/02 3 A

2016/03 4 A

2016/04 5 A

2016/05 4 A

2016/05 4 B.

2016/06 5 B

2016/07 6 B.

日期“2016/05”在我的数据集中出现两次。我想用ggplot2生成条形图。如何使条形图有两个相同的刻度标签?

目标数字是这样的:

r ggplot2 bar-chart
1个回答
1
投票

一种选择是创建一个新的ID列,以便在x轴上具有唯一的类别:

library(tidyverse)

df <- structure(list(Date = c("2016/01", "2016/02", "2016/03", "2016/04", 
                              "2016/05", "2016/05", "2016/06", "2016/07"), 
                     Value = c(2L, 3L,4L, 5L, 4L, 4L, 5L, 6L), 
                     Label = c("A", "A", "A", "A", "A", "B", "B", "B")), .Names = c("Date", "Value", "Label"), 
                row.names = c(NA, -8L), class = c("tbl_df", "tbl", "data.frame"))

df %>%
  unite(ID, Date, Label) %>% 
  ggplot(aes(ID, Value)) +
  geom_col()

enter image description here

或者,您可以使用Label列来表示数据,如下所示:

df %>% 
  ggplot(aes(Date, Value)) +
  geom_col() +
  facet_wrap(.~Label, scales = "free_x")

enter image description here

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