我正在尝试制作带有折线图的条形图。图形已创建好,但是图例不想将线图添加到图例。
我尝试了多种不同的方法将其添加到图例中,包括:
ggplot Legend Bar and Line in Same Graph
没有一个有效。 show.legend
aes中似乎也忽略了geom_line
。
我创建图的代码如下:
ggplot(first_q, aes(fill = Segments)) +
geom_bar(aes(x= Segments, y= number_of_new_customers), stat =
"identity") + theme(axis.text.x = element_blank()) +
scale_y_continuous(expand = c(0, 0), limits = c(0,3000)) +
ylab('Number of Customers') + xlab('Segments') +
ggtitle('Number Customers in Q1 by Segments') +theme(plot.title =
element_text(hjust = 0.5)) +
geom_line(aes(x= Segments, y=count) ,stat="identity",
group = 1, size = 1.5, colour = "darkred", alpha = 0.9, show.legend =
TRUE) +
geom_line(aes(x= Segments, y=bond_count)
,stat="identity", group = 1, size = 1.5, colour = "blue", alpha =
0.9) +
geom_line(aes(x= Segments, y=variable_count)
,stat="identity", group = 1, size = 1.5, colour = "darkgreen",
alpha = 0.9) +
geom_line(aes(x= Segments, y=children_count)
,stat="identity", group = 1, size = 1.5, colour = "orange", alpha
= 0.9) +
guides(fill=guide_legend(title="Segments")) +
scale_color_discrete(name = "Prod", labels = c("count", "bond_count", "variable_count", "children_count)))
我对R还是很陌生,所以如果需要任何进一步的信息,或者如果可以更好地表达这个问题,请告诉我。
非常感谢您的帮助。
答案 0 :(得分:0)
好的,您需要删除一些东西。我使用了mtcars数据集,因为您没有提供。我试图保留您的变量名,并将图简化为必要的部分。代码如下:
null
您链接的答案已经给出了答案,但是我尝试解释一下。您想通过使用数据的不同属性来绘制图例。因此,如果要使用其他行,可以在first_q <- mtcars
first_q$Segments <- mtcars$mpg
first_q$val <- seq(1,nrow(mtcars))
first_q$number_of_new_costumers <- mtcars$hp
first_q$type <- "Line"
ggplot(first_q) +
geom_bar(aes(x= Segments, y= number_of_new_costumers, fill = "Bar"), stat =
"identity") + theme(axis.text.x = element_blank()) +
scale_y_continuous(expand = c(0, 0), limits = c(0,3000)) +
geom_line(aes(x=Segments,y=val, linetype="Line"))+
geom_line(aes(x=Segments,y=disp, linetype="next line"))
中声明。这就是您的图例中显示的内容。所以我在这里使用了两个不同的aes
。由于aes均为geom_lines
,因此两者都显示在图例linetype
上。
您可以轻松地将其适应您的使用。如果您想以这种方式解决问题,请确保使用美观的已知关键字。您也可以使用以下方式更改标题名称:
linetype
如果要添加颜色和相同的线型,可以使用labs(fill = "costum name")
进行自定义,如下所示(我这次没有使用填充来填充条形):
scale_linetype_manual