【问题标题】:Generate a bar graph using ggplot2 and dplyr in R在 R 中使用 ggplot2 和 dplyr 生成条形图
【发布时间】:2020-03-24 23:29:52
【问题描述】:

需要绘制条形图

输出错误:应使用aes() oraes_()` 创建映射。

代码:

cbPalette <- c("#CC79A7", "#D55E00", "#56B4E9", "#F0E442", "#009E73", "#0072B2", "#999999", "#E69F00")

mydata %>%
    group_by(workclass) %>%
    summarise(mean = mean(education.num, na.rm = TRUE)) %>% 
    ggplot(new_data,aes(workclass, education.num, fill = workclass)) +
    geom_bar(stat = "identity") +
    labs(title = "Average Education Num vs workclass",
       x = "Workclass",
       y = "Average Education Num") +
    theme(axis.text.x = element_text(size = 10, angle = 90, hjust = 1))+
    scale_fill_manual(values = cbPalette[1]) +
    theme(axis.text = element_text(size = 10),
        axis.title = element_text(size = 10), 
        legend.title = element_text(size = 10)) +
    scale_fill_manual(values = alpha(cbPalette)) 

任何建议

预期输出:

【问题讨论】:

  • 在致电summarise 后尝试查看您的数据。

标签: r dataframe ggplot2 plot dplyr


【解决方案1】:

您的代码中有几个问题。

1) 当您使用summarise 时,您的列education.num 将在您的数据集中被mean 替换,如下所示:

library(dplyr)

mydata %>%
  group_by(workclass) %>%
  summarise(mean = mean(education.num, na.rm = TRUE))

# A tibble: 9 x 2
  workclass         mean
  <chr>            <dbl>
1 ?                 9.26
2 Federal-gov      11.0 
3 Local-gov        11.0 
4 Never-worked      7.43
5 Private           9.88
6 Self-emp-inc     11.1 
7 Self-emp-not-inc 10.2 
8 State-gov        11.4 
9 Without-pay       9.07

2) 然后,在您的ggplot 中,您正在调用另一个数据帧new_data 并尝试重用education.num 而不是mean。您可以通过以下方式更正它:

library(dplyr)
library(ggplot2)

mydata %>%
  group_by(workclass) %>%
  summarise(mean = mean(education.num, na.rm = TRUE)) %>% 
  ggplot(aes(workclass, mean, fill = workclass)) +
  geom_bar(stat = "identity") +
  labs(title = "Average Education Num vs workclass",
       x = "Workclass",
       y = "Average Education Num") +
  theme(axis.text.x = element_text(size = 10, angle = 90, hjust = 1),
        axis.text = element_text(size = 10),
        axis.title = element_text(size = 10), 
        legend.title = element_text(size = 10)) 

3) 最后,您尝试用 cbPalette 替换填充值,但是,您只提供了 8 个值,而您有 9 个不同的类,因此您需要添加新颜色并像这样删除 ?

library(dplyr)
library(ggplot2)

mydata %>%
  group_by(workclass) %>%
  summarise(mean = mean(education.num, na.rm = TRUE)) %>% 
  filter(workclass != "?") %>%
  ggplot(aes(workclass, mean, fill = workclass)) +
  geom_bar(stat = "identity") +
  labs(title = "Average Education Num vs workclass",
       x = "Workclass",
       y = "Average Education Num") +
  theme(axis.text.x = element_text(size = 10, angle = 90, hjust = 1),
        axis.text = element_text(size = 10),
        axis.title = element_text(size = 10), 
        legend.title = element_text(size = 10)) +
  scale_fill_manual(values = cbPalette) 

它回答了你的问题吗?

【讨论】:

    猜你喜欢
    • 2021-03-14
    • 2023-03-22
    • 1970-01-01
    • 2020-08-02
    • 1970-01-01
    • 2016-07-11
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    相关资源
    最近更新 更多