R: Setting legends and colours in ggplot2
在R中,我试图使用ggplot2绘制条形图和线/点图,但是在图例和颜色设置方面存在困难。
首先,这是我的数据帧。
1 2 3 4 5 6 7 | 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"))) |
我想使用
这是我遇到的问题:
显然,现在我有多余而奇怪的传说。我要拥有的一个图例显示的条形为"总体积",另一个图例显示的每个点/线都表示"自动检测","自动检测","自动检测","自动检测"指挥家ou par l'exploitant","RémontéePOD"。
这个情节的颜色真的很糟糕。我设置了颜色变量
如果有人帮助我解决这些问题,那就太好了。
这是我的尝试。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | 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") |
你可以试试
1 2 3 4 5 | ggplot() + geom_col(data=vol_reshape, aes(x=as.POSIXct(date), y=value, fill=factor("Total"))) + geom_line(data=qua_reshape, aes(x=as.POSIXct(date), y=value2, group=variable, color=variable), size=1.5) + scale_fill_manual(name="", values="skyblue1") + scale_color_manual(values = c("orange", rep(1, 3))) |