我正在尝试根据点的颜色绘制带有点的带有图例的折线图。图表正确绘制,但图例不显示。
图表后面的数据是具有4列的数据框的格式-月,变量(例如特定用户),值(代表分数的数字值)和颜色(基于数字的红色/琥珀色/绿色)得分)。
图表代码如下:
ggplot(data = meltdf2, aes(x = Month, y = variable, group = variable)) +
geom_line(linetype = "dashed", colour = "grey") +
geom_point(colour = meltdf2$colour, size = 3) +
scale_x_date(date_breaks = "1 month" , date_labels = "%b-%y") +
theme(axis.title.y=element_blank(), axis.text.y=element_blank(), axis.ticks.y=element_blank(),
axis.line.x = element_line(colour = "darkgrey"),
panel.background = element_rect(fill = "white"),
panel.grid.major = element_blank(), panel.grid.minor = element_blank())
legend("topleft", legend = c("High", "Mid", "Low"), pch = 1, col= c("red2","gold","limegreen"))
无论我是分别运行绘图还是图例代码还是一起运行,以及是否将它们包含在相同的括号中,都会出现错误:
Error in strwidth(legend, units = "user", cex = cex, font = text.font) : plot.new has not been called yet
任何有关如何显示图例的建议将不胜感激。
答案 0 :(得分:1)
基于以上@ r2evans评论的答案:
问题确实是试图将基础图形命令与ggplot
图形一起使用。
为解决此问题并显示所需的图例,我创建了一个调色板矢量(pal
),其名称基于源数据帧中melt2df$colour
变量的值。此向量作为scale_colour_manual
函数的一部分包含在绘图代码中。 aes
函数中使用了geom_point
函数来包装该系列的各种美学要求。
完成的代码如下所示:
pal <- c("High"="red2","Mid"="gold","Low" = "limegreen","NA"= "NA")
#create plot with line and points.
#colour of points based on colour column of meltdf2
ggplot(data = meltdf2, aes(x = Month, y = variable, group = variable)) +
geom_line(linetype = "dashed", colour = "grey") +
geom_point(aes(colour = meltdf2$colour, size = 3)) +
scale_colour_manual(values = pal, limits = names(pal)) +
scale_x_date(date_breaks = "1 month" , date_labels = "%b-%y") +
theme(axis.title.y=element_blank(), axis.text.y=element_blank(), axis.ticks.y=element_blank(),
axis.line.x = element_line(colour = "darkgrey"),
panel.background = element_rect(fill = "white"),
panel.grid.major = element_blank(), panel.grid.minor = element_blank())