ggplot 将闪避与堆叠条形图相结合
ggplot combine dodge with stacked barplot
我想在 ggplot 中结合条形图的堆叠和闪避样式。我已经很接近这个代码了:
dates_g <- as.Date(c("2020-03-30","2020-03-30", "2020-04-30","2020-04-30", "2020-05-30","2020-05-30"))
value_x <- c(1, 2, 4, 1.4, 3.2, 1.3)
value_y <- c(1.2, 3, 4.6, 1, 3, 1)
ID <- c("A", "B", "A", "B", "A", "B")
results <- data.frame(dates_g, value_x, value_y, ID)
barwidth = 13
bar_comparison <- ggplot() +
geom_bar(data = results[,c(1,2,4)],
mapping = aes(x=dates_g , y=value_x, fill=ID),
stat ="identity",
position = "stack",
width = barwidth) +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) +
geom_bar(data = results[,c(1,3,4)],
mapping = aes(x=dates_g + barwidth + 0.01 , y=value_y, fill=ID),
stat ="identity",
position = "stack",
width = barwidth) +
xlab("Date") + ylab("Value (in millions)")
ggplotly(bar_comparison)
结果是:
我仍然对两件事不满意:我希望日期介于两个条形之间(但这是一个小问题)然后我真的希望每个日期都有不同的颜色两个条:例如,我想让左边的条为绿色(深绿色和浅绿色),右边的条为蓝色(深蓝色和浅蓝色)。可能吗?
这至少是主要问题的解决方案。
我建议使用 facet_wrap
。
为此准备数据 -> 以长格式获取数据,提取日期的月份名称(我为此使用 lubridate
),然后用 ggplot
绘图
library(lubridate)
results_long <- results %>%
pivot_longer(
cols = starts_with("value"),
names_to = "Names",
values_to = "Values"
) %>%
mutate(dates_name = parse_number(as.character(dates_g)),
dates_name = month(ymd(dates_g), label = TRUE))
ggplot(results_long, aes(x = Names, y = Values, fill = ID)) +
geom_bar(stat = 'identity', position = 'stack') + facet_grid(~ dates_name) +
theme_bw()
我想在 ggplot 中结合条形图的堆叠和闪避样式。我已经很接近这个代码了:
dates_g <- as.Date(c("2020-03-30","2020-03-30", "2020-04-30","2020-04-30", "2020-05-30","2020-05-30"))
value_x <- c(1, 2, 4, 1.4, 3.2, 1.3)
value_y <- c(1.2, 3, 4.6, 1, 3, 1)
ID <- c("A", "B", "A", "B", "A", "B")
results <- data.frame(dates_g, value_x, value_y, ID)
barwidth = 13
bar_comparison <- ggplot() +
geom_bar(data = results[,c(1,2,4)],
mapping = aes(x=dates_g , y=value_x, fill=ID),
stat ="identity",
position = "stack",
width = barwidth) +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1)) +
geom_bar(data = results[,c(1,3,4)],
mapping = aes(x=dates_g + barwidth + 0.01 , y=value_y, fill=ID),
stat ="identity",
position = "stack",
width = barwidth) +
xlab("Date") + ylab("Value (in millions)")
ggplotly(bar_comparison)
结果是:
我仍然对两件事不满意:我希望日期介于两个条形之间(但这是一个小问题)然后我真的希望每个日期都有不同的颜色两个条:例如,我想让左边的条为绿色(深绿色和浅绿色),右边的条为蓝色(深蓝色和浅蓝色)。可能吗?
这至少是主要问题的解决方案。
我建议使用 facet_wrap
。
为此准备数据 -> 以长格式获取数据,提取日期的月份名称(我为此使用 lubridate
),然后用 ggplot
library(lubridate)
results_long <- results %>%
pivot_longer(
cols = starts_with("value"),
names_to = "Names",
values_to = "Values"
) %>%
mutate(dates_name = parse_number(as.character(dates_g)),
dates_name = month(ymd(dates_g), label = TRUE))
ggplot(results_long, aes(x = Names, y = Values, fill = ID)) +
geom_bar(stat = 'identity', position = 'stack') + facet_grid(~ dates_name) +
theme_bw()