如何组合柱状条形图

时间:2021-02-24 00:17:48

标签: r ggplot2

我需要使用现有数据绘制此图表。

enter image description here

这就是我的数据的样子。

enter image description here

这是错误:

enter image description here

这是我试过的:

percent_incarcerated <- c(0, 5)
  top_10_black_incarceration_plot <- ggplot(top_10_black_incarceration_states_df)+
  geom_col(aes(x = state, y = percent_incarcerated, fill = c(Black, Total)),
       position = "dodge", stat="identity") + 
  geom_col(position="dodge", stat="identity") 

1 个答案:

答案 0 :(得分:0)

使用您的数据,我能够生成以下内容。

df <- data.frame(
  State = c('LA', 'DC', 'MS', 'GA', 'AL', 'KY', 'PA', 'SC'),
  Black = c(0.6, 0.4, 0.4, 0.3, 0.2, 0.2, 0.2, 0.2),
  Total = c(1.0, 0.4, 0.7, 0.6, 0.5, 0.8, 0.4, 0.4)
)


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

df_long <-df %>%
  pivot_longer(cols = c(Black, Total), names_to = 'Type', values_to = 'Percent_Incarcerated')

df_long %>%
  ggplot(aes(x = Percent_Incarcerated, y = State, fill = Type)) +
  geom_bar(position = 'dodge', stat = 'identity') +
  scale_fill_manual(values = c('black', 'red')) +
  scale_x_continuous(labels = function(x) paste0(x, '%')) +
  labs(
    title = 'States with Highest Rate of Black Incarceration',
    x = 'Percent Incarcerated'
  ) +
  theme(
    legend.title = element_blank()
  )

reprex package (v0.3.0) 于 2021 年 2 月 23 日创建

相关问题