首页 > 解决方案 > 如何将点图中的点与 R 中的因子匹配?

问题描述

我想要下面的 mydf 的点图

mydf <-  data.frame(city=c(rep(c("Rome","NY","LA"),3)),
                           old=c(11,23,13,24,12,13.5,15,17,22),
                           new=c(12,22,13.5,25,14,15,12,17,14),
                            method=c("a","a","a","b","b","b","c","c","c"))
my_cols <- c("red", "blue", " dark green")
grps <- as.factor(mydf$method)
dotchart(mydf$old, labels = mydf$city,
         groups = grps, gcolor = my_cols,
         color = my_cols[grps],
         cex = 0.6,  pch = 19, xlab = "value")
meth1<- mydf[mydf$method=="a",]
meth2<- mydf[mydf$method=="b",]
meth3<- mydf[mydf$method=="c",]
points(meth1$new, 1:nrow(meth1), col = "orange", pch = 16, cex = 0.6)
points(meth2$new, 1:nrow(meth2), col = "light blue", pch = 16, cex = 0.6)
points(meth2$new, 1:nrow(meth2), col = "green", pch = 16, cex = 0.6)

在添加点()之前,我得到了下面的图,这是我想要的基础。 在此处输入图像描述

但是当我添加点时,它们都出现在图的底部。我希望与每种方法对应的“新”值出现在绘图的其自己的部分中,并且一条线段相应地连接旧值和新值。

在此处输入图像描述 我怎么能在我的代码中做到这一点?感谢您对此的任何帮助。

标签: rggplot2plotgraphdot

解决方案


点图中的 y 轴实际上只是整数。因此,您必须提供正确的 y 轴值points()

points(meth1$new, 11:13, col = "orange", pch = 16, cex = 0.6)
points(meth2$new, 6:8, col = "light blue", pch = 16, cex = 0.6)
points(meth2$new, 1:3, col = "green", pch = 16, cex = 0.6)

我只是通过观察情节并数数来达到这些值。请注意,如果这些点超出原始dotchart调用的范围,则并非所有这些点都会出现。您可以通过设置xlim = c(11,25)dotchart呼叫中的适当内容来调整它。


推荐阅读