【发布时间】:2018-10-28 17:57:00
【问题描述】:
在 R 中,我正在尝试使用 ggplot2 绘制条形图和线/点图,但我在图例和颜色设置方面遇到了困难。
首先,这是我的数据框。
vol_reshape <- data.frame(date = c("2018-01-01", "2018-02-01", "2018-03-01", "2018-04-01"),
variable = rep("total", 4),
value = as.integer(c("8029", "8164", "9536", "9482")))
qua_reshape <- data.frame(date = rep(c("2018-01-01", "2018-02-01", "2018-03-01", "2018-04-01"), 4),
variable = c(rep("quality_1", 4), rep("quality_2", 4), rep("quality_3", 4), rep("pod", 4)),
value = as.double(c("0.26", "0.26", "0.30", "0.32", "0.27", "0.27", "0.30", "0.32", "0.45", "0.42", "0.51", "0.55", "0.05", "0.04", "0.05", "0.05")))
我想使用vol_reshape 绘制一个条形图,在这个条形图上,我想使用qua_reshape 绘制点和线。这是我的输出。
这是我遇到的问题:
- 传说
显然现在我有多余的和奇怪的传说。我想要的是一个图例显示该栏是“总体积”,另一个图例显示每个点/线表示“Détectée automatique”、“Détectée automatique ou déclarée par leconducteur”、“Détectée automatique,déclarée par le conducteur ou par l'exploitant”、“Rémontée POD”。
- 颜色
这个情节的颜色真的很糟糕。我将颜色变量cols 设置为蓝色,三个线/点(quality_1 ~ 3)为黑色,pod 线/点为橙色。我在scale_fill_manual 中设置了这些值,但这并不能反映我的愿望。
如果有人帮我解决这些问题,那就太好了。
这是我的尝试。
p <- ggplot(data = vol_reshape[which(vol_reshape$value > 0),],
aes(x = date, y = value, label = value,
fill = variable
)
) +
geom_bar(stat = "identity", position = "stack", show.legend = T) +
theme(legend.title=element_blank()) +
geom_text(size = size$label, position = position_stack(vjust = 0.9), color = "#FFFFFF") +
geom_point(data = qua_reshape, mapping = aes(x = date,
y = value *max(vol_reshape$value),
color = quality
)
) +
theme(legend.title=element_blank()) +
geom_line(data = qua_reshape, mapping = aes(x = date,
y =value*max(vol_reshape$value),
color = variable),
size = size$line) +
geom_text(data = qua_reshape, mapping = aes(x = date,
y =value*max(vol_reshape$value),
label =paste0(100*value, '%'),
color = variable),
size = size$label, vjust = -0.9, hjust = 1.5
) +
theme_classic() +
scale_y_continuous(sec.axis = sec_axis(trans = ~.*(1/max(vol_reshape$value)))) +
scale_fill_manual(name = NULL, values = cols, labels = labs, drop = T) +
theme(legend.position = "right",
plot.title = element_text(hjust = 0.5, size = size$title, family="Proxima Nova"),
plot.subtitle = element_text(size = size$subtitle, family="Proxima Nova"),
axis.title.x=element_blank(),
axis.text.x = element_text(angle = 45, margin=margin(t = 8),
family="Proxima Nova"))
)
cols <- c("total" = "#3D8BDA", "quality_1" = "#000000", "quality_2" ="#000000", "quality_3" = "#000000", "pod" = "#ff8142")
labs <- c("Total", "Détectée automatique", "Détectée automatique ou déclarée par le conducteur", "Détectée automatique, déclarée par le conducteur ou par l'exploitant", "Rémontée POD")
【问题讨论】: