如何在 ggplot R 中自定义条形图?

How to costumize bar chart in ggplot R?

我有一个镜像条形图,我想避免镜像条形图并有相同的图表,但每个类别有 2 列:

  1. 负值和正值(右侧为正值,左侧为负值)
  2. 颜色必须由 'Model' 分类变量确定,pos 和 neg 值需要不同,例如全彩色条 = 正,有界(具有相同颜色)但未填充条 = 负。
  3. 此外,基于美国的值必须位于顶部,基于加拿大的值必须位于下方
df <- data.frame (Origin = c("Canada", "Canada","Canada", "Canada","Canada", "Canada","USA","USA","USA","USA","USA","USA"),
                  Model = c("A","B","C","D","E","F","A","B","C","D","E","F"),
                  poschange = c(60, 45,34,56, 65, 44,40, 55, 35, 24,34,12),
                  negchange = c(-5,-2,-0.5,-2,-1,-0.05,-1,-3,-0.1,-3,-1.5,-0.9))

require(dplyr)
require(ggplot2)
require(tidyr)


df2 <- df %>% pivot_longer(., cols=c('poschange','negchange'),
                           names_to = 'value_category')
df2 <- df2 %>% mutate(Groups = paste(Origin, Model))
df2 <- df2 %>% mutate(label_position=ifelse(value>0, value-5,value-8)) # adjusting label position
df2 %>% arrange(value) %>% ggplot(aes(x=value, y=reorder(Groups,value), 
                                      fill=value_category, 
                                      group=value_category))+
  geom_col(width=0.75)
coord_flip()

输出:

期望的输出(类似这样,但颜色必须对应于型号类别变量):

也许是这样的?

  1. 使用 ifelse 语句将负值标记为“白色”
  2. 要获得 fill 白色,请使用 scale_fill_manualmy_color 调色板
  3. 要避免“镜像”条,请使用 position = "dodge"
  4. 要获得负值和正值 side-by-side,您需要在 ggplot
  5. 中交换 xy 参数
  6. 要避免 x-axis 上的文本重叠,请使用 theme(axis.text.x = element_text(angle = 90))
  7. 在两个 scale_xxx_manual 函数中使用 breaks 参数来删除图例中的“白色”标签
library(tidyverse)
df <- data.frame (Origin = c("Canada", "Canada","Canada", "Canada","Canada", "Canada","USA","USA","USA","USA","USA","USA"),
                  Model = c("A","B","C","D","E","F","A","B","C","D","E","F"),
                  poschange = c(60, 45,34,56, 65, 44,40, 55, 35, 24,34,12),
                  negchange = c(-5,-2,-0.5,-2,-1,-0.05,-1,-3,-0.1,-3,-1.5,-0.9))

df2 <- df %>% pivot_longer(., cols=c('poschange','negchange'),
                           names_to = 'value_category') %>% 
  mutate(Groups = paste(Origin, Model),
         value_category = factor(value_category, levels = c("negchange", "poschange")))

my_color = c("A" = '#7fc97f', "B" = '#beaed4', "C" = '#fdc086', 
             "D" = '#ffff99', "E" = '#386cb0', "F" = '#f0027f', "white" = "white")

ggplot(df2, aes(value, Model, 
                fill = ifelse(value_category == "negchange", "white", Model), 
                color = Model)) + 
  geom_col(position = "dodge") +
  scale_fill_manual(values = my_color, breaks = df2$Model) +
  scale_color_manual(values = my_color, breaks = df2$Model) +
  labs(fill = "Model") +
  facet_grid(Origin ~ ., switch = "y") +
  theme(axis.text.x = element_text(angle = 90),
        strip.background = element_rect(fill = "white"),
        strip.placement = "outside",
        strip.text.y.left = element_text(angle = 0),
        panel.spacing = unit(0, "lines"))

reprex package (v2.0.1)

于 2022-05-03 创建