ggplot 条形图 (geom_bar) 使用DF的起点和终点

ggplot bar chart (geom_bar) to use start and end point from df

提问人:Subaru Spirit 提问时间:8/6/2021 更新时间:8/6/2021 访问量:863

问:

我下面有 2 个标签,A 和 B。我希望 A 的条形图从 0 到 2,B 的条形图从 3 到 6。我该怎么做?如果需要争吵来做到这一点,那也没关系。dfdf

df <- data.frame(labels = c("A", "A", "B", "B"), values = c(0, 2, 3,6))

ggplot(df, aes(x = labels, y = values, fill = labels, colour = labels)) + 
  geom_bar(stat = "identity")
r ggplot2

评论


答:

3赞 stefan 8/6/2021 #1

实现所需结果的一种选择是利用它涉及一些数据整理来使数据形成正确的形状:geom_rect

library(ggplot2)
library(dplyr)
library(tidyr)

df <- data.frame(labels = c("A", "A", "B", "B"), values = c(0, 2, 3, 6))

df <- df %>% 
  group_by(labels) %>% 
  arrange(values) %>% 
  mutate(id = row_number()) %>% 
  ungroup() %>% 
  pivot_wider(names_from = id, values_from = values) %>% 
  rename(ymin = 2, ymax = 3) %>% 
  mutate(xmin = as.numeric(factor(labels)) - .45,
         xmax = as.numeric(factor(labels)) + .45)

ggplot(df, aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, fill = labels, colour = labels)) + 
  geom_rect(stat = "identity") +
  scale_x_continuous(breaks = 1:2, labels = c("A", "B"))