为什么ggplot2图例不显示在图中 [英] Why ggplot2 legend not show in the graph

查看:1619
本文介绍了为什么ggplot2图例不显示在图中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ggplot散布图2数据集,并想在左上角显示图例。我尝试了一些代码,但没有工作。

  ggplot(mf,aes(log10(mf [,2]),mf [, 1)))
+ ggtitle(Plot)
+ geom_point(color =blue)+ theme(plot.margin = unit(c(1,2,1,1),cm ))
+ xlab(xxx)+ ylab(yyy)
+ theme(plot.title = element_text(size = 18,hjust = 0.5,vjust = 4))
+ geom_point(data = mf2,aes(log10(mf2 [,2]),mf2 [,1]),color =red)
+ theme(axis.title.x = element_text(size = rel (1.3)))
+ theme(axis.title.y = element_text(size = rel(1.3)))
+ scale_color_discrete(name =Dataset,labels = c(Dataset 1, 数据集2))

解决方案

由于未提供值,因此我已将自己的值用于演示目的。



mf 是一个 dataframe ,其中 log a nd val ,因为它是列。



您需要将颜色参数放在美学内。这将导致图例的颜色映射。之后,您可以手动缩放颜色以获得您想要的任何颜色。



您可以使用以下代码来获得所需的结果。

  ggplot(mf,aes(val,log))+ 
geom_point(aes(color =Dataset1))+
geom_point data = mf2,aes(color =Dataset2))+
labs(color =Datasets,x =xxx,y =yyy)+
theme(legend.position = c (0,1),legend.justification = c(0,1))+
scale_color_manual(values = c(blue,red))
pre>


I use ggplot to scatterplot 2 datasets and want to show the legend in the top left. I tried some code but didn't work. I am not sure why this happened.

ggplot(mf, aes(log10(mf[,2]),mf[,1])) 
+ ggtitle("Plot") 
+ geom_point(color = "blue") +  theme(plot.margin = unit(c(1,2,1,1), "cm"))
+ xlab("xxx") + ylab("yyy") 
+ theme(plot.title = element_text(size=18,hjust = 0.5, vjust=4)) 
+ geom_point(data=mf2,aes(log10(mf2[,2]),mf2[,1]),color="red") 
+ theme(axis.title.x = element_text(size = rel(1.3))) 
+ theme(axis.title.y = element_text(size = rel(1.3))) 
+ scale_color_discrete(name = "Dataset",labels = c("Dataset 1", "Dataset 2"))

解决方案

Since values were not provided, I have used my own values for the demonstration purpose.

mf is a dataframe with log and val as it's column.

You need to put the color parameter inside the aesthetics. This will result in the mapping of colors for the legend. After that you can manually scale the color to get any color you desire.

you can use the below code to get the desired result.

ggplot(mf, aes(val,log))+
    geom_point(aes(color = "Dataset1"))+
    geom_point(data=mf2,aes(color="Dataset2"))+
    labs(colour="Datasets",x="xxx",y="yyy")+
    theme(legend.position = c(0, 1),legend.justification = c(0, 1))+
    scale_color_manual(values = c("blue","red"))

这篇关于为什么ggplot2图例不显示在图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆