r - ggplot2:按字母顺序排列图例,而不是按照数据集中出现的顺序

标签 r csv ggplot2 legend

我正在从 AESRD 2013 - SCO Bitumen - 7y.csv 生成 ggplot2 线图in this folder .该文件是根据我的意愿在网站上自动创建的。这些是显示一些生产值的几个时间序列,每个值都根据“编译”列命名。所以我按照“编译”分组。

请参阅文件 plotter.r 中我的代码的摘录在同一文件夹中可用(见上文)。

# "dt" is the dataframe derived from the csv file. 
# "thinned" is some vector of x-values that tells where to draw the special symbols.

p = ggplot(dt, aes(Date, Value, colour= Compilation, group = Compilation, size = plotParameter), guide=FALSE)
p = p + geom_point(data=dt[thinned,],aes(as.Date(Date), Value, colour= Compilation, shape = Compilation), size = 5)
p = p + scale_shape_manual(values = seq(0,20))
p = p + geom_line(guide = FALSE)
p = p + scale_colour_manual(values=cbPalette) #cbPalette is already defined
p = p + scale_size(range=c(0.5, 2), guide=FALSE)
p = p + scale_y_continuous(labels = comma)
p = p + ylab("Barrels per day") + xlab("")
p = p + theme(legend.text = element_text(size = 8, hjust = 5, vjust= -5)) 
plot(p)

讨厌的事情来了:图例对我的合辑重新排序 按字母顺序 !
enter image description here

我特意设计了我的 csv 文件,以便每个编译都以特定的逻辑顺序显示(首先是最重要的系列,然后按照某些性能参数的顺序)。所以图例的正确顺序应该是根据 unique(dt$Compilation) .

我到现在的步骤是介绍专栏Order进入 csv 文件并进行实验(不成功),并以各种方式更改我的代码。没有成功。

当然,我已经在 Stackoverflow 上搜索并检查了大多数可用线程。我遇到了分解和重新排序,但除了它们在数据集中出现的顺序之外,我的编译没有“逻辑”顺序。 *叹*

谁能指点我哪里插入 什么 ?

(加分点:我如何摆脱符号图例中的那些水平线?)

最佳答案

申请 breaks在两个尺度( scale_color_manualscale_shape_manual )。如果我们只做一个,它们就不会匹配,ggplot 会将它们分成两个图例,而不是合并它们

一个这样的例子是:

> library(ggplot2)
> ggplot(mtcars, aes(wt, mpg, shape=factor(cyl))) + geom_point() + theme_bw()
> library(ggplot2)
> bp <- ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group)) + geom_boxplot()
> bp

enter image description here
bp + scale_fill_discrete(breaks=c("trt1","ctrl","trt2"))

enter image description here

扭转
bp + scale_fill_discrete(breaks = rev(levels(PlantGrowth$group)))

也试试
bp + scale_fill_discrete(breaks = unique(levels(PlantGrowth$group)))

关于r - ggplot2:按字母顺序排列图例,而不是按照数据集中出现的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21403511/

相关文章:

java - 我可以将多个testng报告合并为一个吗?

r - 如何将ggplot标题与窗口而不是绘图网格对齐?

r - 散点图 : Error in FUN(X[[i]], ...):找不到对象 'Group'

r - 在堆叠的ggplot2条形图中打印组x轴标签

r - 不能在 R 中使用很棒的字体

r - 从全名中分离姓氏

删除绘图轴值

受限玻尔兹曼机

r - Google 文档导出带有逗号的电子表格值。 R 中的 read.csv() 将这些视为因素而不是数字

csv - 在 Go 中高效读写 CSV