条形图在ggplot中按组显示颜色
Bar plot shows color by group in ggplot
我的数据框如下:
df2 <- structure(list(City = c("Naypyitaw", "Yangon", "Yangon", "Naypyitaw",
"Mandalay", "Mandalay", "Mandalay", "Naypyitaw", "Yangon"), month = structure(c(1L,
1L, 3L, 3L, 1L, 3L, 2L, 2L, 2L), .Label = c("Jan", "Feb", "Mar",
"Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
), class = "factor"), gross.income = c(1925.461, 1841.9585, 1793.2915,
1771.383, 1770.2885, 1647.4925, 1639.251, 1568.3325, 1421.9105
)), row.names = c(NA, -9L), groups = structure(list(City = c("Mandalay",
"Naypyitaw", "Yangon"), .rows = structure(list(5:7, c(1L, 4L,
8L), c(2L, 3L, 9L)), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), row.names = c(NA, -3L), class = c("tbl_df",
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"))
我正在尝试再次绘制条形图几个月 gross.income。虽然我得到的情节如下:
我不要按组的颜色。我想要这样的东西:
我的代码:
df2$month <- factor(df2$month, levels = month.abb)
plot3 <- ggplot(df2, aes(x = month, y = gross.income, fill = gross.income)) +
geom_bar(stat = "identity") +
scale_x_discrete(limits = month.abb[1:3])
如果每个条只需要一种颜色,则每个 month
只需要一个条目。因此,您需要在 ggplot()
.
之前 summarise
您的数据
library(tidyverse)
df2 %>%
group_by(month) %>%
summarize(gross.income = sum(gross.income)) %>%
ggplot(aes(month, gross.income, fill = gross.income)) +
geom_bar(stat = "identity")
由 reprex package (v2.0.1)
于 2022 年 3 月 12 日创建
我的数据框如下:
df2 <- structure(list(City = c("Naypyitaw", "Yangon", "Yangon", "Naypyitaw",
"Mandalay", "Mandalay", "Mandalay", "Naypyitaw", "Yangon"), month = structure(c(1L,
1L, 3L, 3L, 1L, 3L, 2L, 2L, 2L), .Label = c("Jan", "Feb", "Mar",
"Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
), class = "factor"), gross.income = c(1925.461, 1841.9585, 1793.2915,
1771.383, 1770.2885, 1647.4925, 1639.251, 1568.3325, 1421.9105
)), row.names = c(NA, -9L), groups = structure(list(City = c("Mandalay",
"Naypyitaw", "Yangon"), .rows = structure(list(5:7, c(1L, 4L,
8L), c(2L, 3L, 9L)), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), row.names = c(NA, -3L), class = c("tbl_df",
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"))
我正在尝试再次绘制条形图几个月 gross.income。虽然我得到的情节如下:
我不要按组的颜色。我想要这样的东西:
我的代码:
df2$month <- factor(df2$month, levels = month.abb)
plot3 <- ggplot(df2, aes(x = month, y = gross.income, fill = gross.income)) +
geom_bar(stat = "identity") +
scale_x_discrete(limits = month.abb[1:3])
如果每个条只需要一种颜色,则每个 month
只需要一个条目。因此,您需要在 ggplot()
.
summarise
您的数据
library(tidyverse)
df2 %>%
group_by(month) %>%
summarize(gross.income = sum(gross.income)) %>%
ggplot(aes(month, gross.income, fill = gross.income)) +
geom_bar(stat = "identity")
由 reprex package (v2.0.1)
于 2022 年 3 月 12 日创建