如何更改填充“名称”,即:psavert为“个人储蓄率”,“uempmed”为“中位数失业持续时间” 我还想在7 y轴的回报中添加%符号,无法使用scale_x_discrete()并对其进行修改。
有人可以帮忙吗?
附件是图像,下面是代码
library(ggplot2)
library(lubridate)
theme_set(theme_bw())
df <- economics[, c("date", "psavert", "uempmed")]
df <- df[lubridate::year(df$date) %in% c(1967:1981), ]
# labels and breaks for X axis text
brks <- df$date[seq(1, length(df$date), 12)]
lbls <- lubridate::year(brks)
# plot
ggplot(df, aes(x=date)) +
geom_area(aes(y=psavert+uempmed, fill="psavert")) +
geom_area(aes(y=uempmed, fill="uempmed")) +
labs(title="Area Chart of Returns Percentage",
subtitle="From Wide Data format",
caption="Source: Economics",
y="Returns %") + # title and caption
scale_x_date(labels = lbls, breaks = brks) + # change to monthly ticks and
labels
scale_fill_manual(name="",
values = c("psavert"="#00ba38", "uempmed"="#f8766d")) + #
line color
theme(panel.grid.minor = element_blank()) + # turn off minor grid
annotate("text", x=as.Date("1975-04-01"), y=25, label="Year with highest returns") #annotation layer
答案 0 :(得分:1)
下面的第一个示例是如何使用原始绘图代码。第二种是更“类似ggplot”的方法,它首先将数据重新整形为“长”格式并重新编码值的名称。
library(tidyverse)
library(lubridate)
theme_set(theme_bw() + theme(panel.grid.minor=element_blank()))
ggplot(df, aes(x=date)) +
geom_area(aes(y=psavert+uempmed, fill="Personal Saving Rate")) +
geom_area(aes(y=uempmed, fill="Unemployment Rate")) +
labs(title="Area Chart of Returns Percentage",
subtitle="From Wide Data format",
caption="Source: Economics",
y="Returns %") + # title and caption
scale_x_date(labels = lbls, breaks = brks) + # change to monthly ticks and labels
scale_fill_manual(name="",
values = c("Personal Saving Rate"="#00ba38", "Unemployment Rate"="#f8766d")) + # line color
scale_y_continuous(breaks=seq(0,30,10), labels=paste0(seq(0,30,10),"%")) +
annotate("text", x=as.Date("1975-04-01"), y=25, label="Year with highest returns")
下面的替代方法也使用date_breaks
的{{1}}和date_labels
参数,因此在创建绘图之前无需创建中断和标签向量。
scale_x_date