且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

订购了ggplot2 dotplot with facet

更新时间:2023-11-26 12:17:16

您可以使用因子和一个指定级别顺序的字符向量来命令级别:

  d $ ind   

这里, unique(d $ ind)以数据框中出现的顺序返回值。这是颜色比例的级别顺序。



您想为 y 轴。默认情况下,订单是从下到上。您可以创建第二个变量 ind2 ,并使用颠倒的顺序:

  d $ ind2   

这将被用作 y 轴的变量。

  library(ggplot2)
ggplot(d,aes(x = values,y = ind2,color = ind))+
geom_point()+ facet_wrap(〜Year,ncol = 1)


I am replicating a version of this dotplot http://blogs.bgsu.edu/math6820cwenren/files/2011/04/ggplot-dotplot.png from http://blogs.bgsu.edu/math6820cwenren/2011/04/27/ggplot2/. Code is below.

I would like the plot and the key to match in the order of presentation. This could be accomplished by reordering the variable ind to appear as in the plot, i.e., Tracy, LeBron, Kobe, Anthony. Or vice-versa and reorder the key. I've tried reordering the factors with several methods but the order in key is always reverse the order in the plot.

How to reorder so the presentation is consistent?

Kobe=c(31.6, 28.3, 26.8, 27.0, 24.8)
LeBron=c(27.3, 30.0, 28.4, 29.7, 26.0)
Tracy=c(24.6, 21.6, 15.6, 8.6, 8.5)
Anthony=c(28.9, 25.7, 22.8, 28.2, 25.3)
year=c(2006, 2007, 2008, 2009, 2010)

data1=cbind(Kobe, LeBron, Tracy, Anthony)

data=data.frame(data1,row.names=year)

d=data.frame(Year=dimnames(data)[[1]],stack(data))

p=ggplot(d, aes(values, ind, color=ind))
p + geom_point()+ facet_wrap(~Year, ncol=1)

You can order the levels with factor and a character vector specifying the order of levels:

d$ind <- factor(d$ind, levels = unique(d$ind))

Here, unique(d$ind) returns the values in the order of appearance in the data frame. This is the order of levels for the color scale.

You want a reversed order of levels for the y axis. By default, the order is bottom to top. You can create a second variable, ind2, with reversed level order:

d$ind2 <- factor(d$ind, levels = rev(levels(d$ind)))

This will be used as the variable for the y axis.

library(ggplot2)
ggplot(d, aes(x = values, y = ind2, color = ind)) +
  geom_point() + facet_wrap(~ Year, ncol = 1)