我想知道是否可以帮助我以这个图中所示的方式绘制我的数据
仅显示来自df1或df2
的数据的两种颜色Y轴,假设两个数据帧的第一个值
df1是
Var1 Freq
1 2 252
和df2是
Var1 Freq
1 2 306
所以,取而代之的是Y轴上的名字,我希望是2,然后是252中的点(显示df1的值)和306上的点(显示df2的值)和两个节目之间的暗线两个值之间的距离
两个数据的Var1范围是不同的,所以对于df1,我们有一些我们没有df2的点,我们可以只为一个存在的点绘制一个点
我们根据Y轴将数据分为非洲,AMrecia和亚洲三部分
2 to 10
10 to 20
Higher than 20
我可以用简单的线条形状甚至是频率形状绘制它,但是这个情节我发现它非常困难,我甚至无法获得它的线条。我将不胜感激任何帮助
我首先尝试合并失败的数据,因为Var1中的某些数据不存在于
中m=merge(df1,df2,by="Var1")
答案 0 :(得分:1)
试试这个:
df <- merge(df1, df2, by='Var1', all=TRUE)
df$Var1 <- as.integer(as.character(df$Var1))
df$Continent <- cut(df$Var1, breaks = c(-Inf, 10, 20, Inf), labels= c('Africa', 'America', 'Asia'))
par(mfrow=c(3,1), mar=c(4,4,1,1), oma=c(1.5,2,1,1))
x.min <- min(c(df$Freq.x, df$Freq.y), na.rm=TRUE)
x.max <- max(c(df$Freq.x, df$Freq.y), na.rm=TRUE)
for (continent in unique(df$Continent)) {
df3 <- df[df$Continent == continent,]
plot(df3$Freq.x, df3$Var1, pch=19, col='red', cex=1.2,
xlim=c(x.min, x.max),
xlab='Freq', ylab=continent)
points(df3$Freq.y, df3$Var1, pch=19, col='blue', cex=1.2)
segments(df3$Freq.x, df3$Var1, df3$Freq.y, df3$Var1, col='gray')
}
title(main="3 Continents of Colonialism", outer=TRUE)
更新了您的新要求:
df <- merge(df1, df2, by='Var1', all=TRUE)
df$Var1 <- as.integer(as.character(df$Var1))
df$Continent <- cut(df$Var1, breaks = c(-Inf, 10, 20, Inf), labels=
c('Africa', 'America', 'Asia'))
par(mfrow=c(3,1), mar=c(4,4,1,1), oma=c(1.5,2,1,1))
x.min <- 0
x.max <- c(300, 50, 10)
xlab <- c('', '', 'Freq')
i <- 1
for (continent in unique(df$Continent)) {
df3 <- df[df$Continent == continent,]
plot(df3$Freq.x, df3$Var1, pch=19, col='red', cex=1.5,
xlim=c(x.min, x.max[i]),
xlab=xlab[i], ylab=continent)
par(xpd=FALSE)
grid (lty = 6, col = "cornsilk2")
par(xpd=TRUE)
points(df3$Freq.y, df3$Var1, pch=19, col='blue', cex=1.5)
segments(df3$Freq.x, df3$Var1, df3$Freq.y, df3$Var1, col='gray', lwd = 2)
i <- i + 1
}
title(main="3 Continents of Colonialism", outer=TRUE)
legend(x=8.6, y=0, legend = c("DF1", "DF2"),
col=c("red", "blue"), pch=19, xpd=NA, bty="o")
答案 1 :(得分:1)
使用ggplot2
library(ggplot2)
ggplot(df, aes(Freq.x, Var1)) +
geom_point(col='red') +
geom_point(aes(Freq.y, Var1), col='blue') +
geom_segment(aes(xend=Freq.y, yend=Var1), col='gray') +
facet_wrap(~Continent, ncol=1, scales = 'free') +
xlab('Freq') +
ylab('Var') +
ggtitle('3 Continents of Colonialism')+
theme_bw()