简体   繁体   English

在R / ggplot2中修改图例和堆积区域图的标签

[英]Modify legend and labels of stacked-area plot in R/ggplot2

EDIT: Solved by Haboryme in comments; 编辑:在评论中由Haboryme解决; the problem was my use of xlab and ylab instead of x and y as the names of keyword arguments to labs() (explaining the graph labels), and a redundant use of colour= in the second call to aes() (explaining the persistence of the original legend). 问题是我使用xlab和ylab代替x和y作为labs()的关键字参数的名称(解释图形标签),以及在对aes()的第二次调用中冗余使用colour =(解释持久性)原始图例)。

I'd like to make a stacked-area chart from some CSV data with R and ggplot2. 我想用R和ggplot2从一些CSV数据制作一个堆积面积图。 For example: 例如:

In file "test.csv":
Year,Column with long name 1,Column with long name 2
2000,1,1
2001,1,1.5
2002,1.5,2

I run this code (imitating the answer to this GIS.SE question ): 我运行以下代码(模仿此GIS.SE问题的答案):

library(ggplot2)
library(reshape)
df <- read.csv('test.csv')
df <- melt(df, id="Year")
png(filename="test.png")
gg <- ggplot(df,aes(x=as.numeric(Year),y=value)) +
    # Add a new legend
    scale_fill_discrete(name="Series", labels=c("Foo bar", "Baz quux")) +
    geom_area(aes(colour=variable,fill=variable)) +
    # Change the axis labels and add a title
    labs(title="Test",xlab="Year",ylab="Values")
print(gg)
dev.off()

The result, in file "test.png": 结果在文件“ test.png”中:

具有错误的轴标签和额外图例的堆叠区域图

Problems: my attempt to change the axis labels was ignored, and my new legend (with code borrowed from the R Cookbook's suggestions ) was added to, not substituted for, the (strangely recolored) default one. 问题:我更改轴标签的尝试被忽略,我的新图例(从R Cookbook的建议中借来了代码)被添加到(替代了)(奇怪地重新着色)默认值中。 (Other solutions offered by the R Cookbook, such as calling guides(fill=FALSE), do more or less the same thing.) I'd rather not use the workaround of editing my dataframe (eg stripping the periods that read.csv() substitutes for spaces in column headers) so that the default labels turn out correct. (R Cookbook提供的其他解决方案,例如调用guides(fill = FALSE),或多或少都做同样的事情。)我宁愿不使用编辑数据帧的变通方法(例如,删除read.csv( )替换列标题中的空格),以使默认标签正确无误。 What should I do? 我该怎么办?

ggplot(df,aes(x=as.numeric(Year),y=value)) +
  scale_fill_discrete(name="Series", labels=c("Foo bar", "Baz quux")) +
  geom_area(aes(fill=variable)) +
  labs(title="Test",x="Year",y="Values")

The argument colour in the aes() of geom_area() only colours the contour and hence doesn't add anything to the plot here. geom_area()aes()中的参数colour仅为轮廓geom_area() ,因此在此处不向绘图添加任何内容。

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

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