简体   繁体   English

R:如何用ggplot2绘制两种不同类型的图?

[英]R : How to plot two different kind of plot with ggplot2?

My data is like this : 我的数据是这样的:

id <- c('a','a','b','b')
var <- c('Var1','Var2','Var1','Var2')
value <- c(123,421,2132,633)
df <- cbind(id,var,value)

I would like to plot a scatter plot of Var1 and a bar chart of Var2 , with a legend showing that the dot is Var1 and the Bar is Var2 我想绘制Var1的散点图和Var2的条形图,图例显示点是Var1而Bar是Var2

I have tried these code : 我已经尝试过这些代码:

g <- ggplot(data = df, aes(x=id, y=value, fill=var)
g + stat_identity(geom = c("point","bar"))

But both Var1 and Var2 are showed in scatter point in this way. 但是Var1Var2都以这种方式显示在散点上。

I also tried to create two seprate data for Var1 and Var2 . 我还尝试为Var1Var2创建两个单独的数据。

id = c('a','b')
Var1 = c(123,2132)
Var2 = c(421,633)
df1 = cbind.data.frame(id, Var1)
df2 = cbind.data.frame(id, Var2)

g <- ggplot()
g + geom_point(data = df1, aes(x=id, y=Var1),stat = "identity")) +
    geom_bar(data = df2, aes(x=id, y=Var2),stat = "identity"))

In this way, I can combine a scatter point with a bar chart, but there is no legend and I don't know how to make the legend telling readers that the dot is Var1 and the bar is Var2 这样,我可以将散点图和条形图结合起来,但是没有图例,而且我不知道如何使图例告诉读者点是Var1 ,条形图是Var2

First off, see this post . 首先,请参阅这篇文章 Thanks @Daniel! 谢谢@丹尼尔!

You could try this: 您可以尝试以下方法:

id = c('a','b')
Var1 = c(123,2132)
Var2 = c(421,633)
df1 = cbind.data.frame(id, Var1)
df2 = cbind.data.frame(id, Var2)
library(ggplot2)
g <- ggplot()
g + geom_bar(data = df2, aes(x=id, y=Var2, fill = 'Var2'),stat = "identity")+
     geom_point(data = df1, aes(x=id, y=Var1, colour = 'Var1'),stat = "identity", size = 2) +
    scale_fill_manual(values = c('Var2' = 'blue'), name = 'Bars')+
    scale_colour_manual(values = c('Var1' = 'red'), name = 'Dots')

在此处输入图片说明

Basically, we use the aes within geom_point and geom_bar to define our color or fill. 基本上,我们使用geom_pointgeom_baraes定义颜色或填充。 Then use scale_*_manual to control display. 然后使用scale_*_manual来控制显示。 Also, we call geom_bar before geom_point so that the dots are plotted over the bar. 另外,我们称之为geom_bar 之前 geom_point ,这样的点绘制高出横梁。 Also, I use size = 2 in geom_point so that the point is a little more distinguishable. 另外,我在geom_point使用size = 2 ,以便该点更具区别性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM