如何更改R中的图例标签(ggplot2)

时间:2019-01-29 16:35:53

标签: r ggplot2

我想更改此图的图例标签: enter image description here

基本上要转换为实际值乘以100(以便以%表示)。我在向量中保存了要在已修改的标签上使用的值,并保存为字符串,但是当我使用scale_color_manual时,我需要指定其他不确定它们是什么的东西。这是我的代码:

library(tidyverse)

#Get desired amounts

month_income <- seq(500,10000, by = 500)

#Get average monthly % growth

month_perc <- seq(0.03, 0.1, by = 0.01)
perc_vals <- length(month_perc)
perc_title <- as.character(month_perc * 100)

#Preparate data

month_income <- rep(month_income, length(month_perc))

month_perc <- rep(month_perc, length(month_income) / perc_vals) %>% sort()

#Calculate account size and build data frame

dat <- data.frame(Desired_Income = month_income, Monthly_Gain = month_perc, Account_Size = month_income / month_perc)

dat <- dat %>% mutate(Monthly_Gain = as.factor(Monthly_Gain))

#Plot it

dat %>% ggplot(aes(Desired_Income/1000, Account_Size/1000, color = Monthly_Gain)) +
  geom_point() +
  geom_line() +
  xlab("Desired Income in Thousand Dollars") +
  ylab("Required Account Size in Thousand Dollars") + 
  ggtitle("3% to 5% per month account growth") + 
  labs(col = "Monthly Gain") +
  theme(plot.title = element_text(hjust=0.5))

是否有一个像ggtitle()一样的图层,我可以用来在其中传递带有标签的矢量?

1 个答案:

答案 0 :(得分:1)

就个人而言,我只需要添加一列包含转换后的值,而不是:

dat <- dat %>% mutate(Monthly_Gain = as.factor(Monthly_Gain))

我会使用:

dat <- dat %>% mutate(`Monthly_Gain_%` = as.factor(Monthly_Gain * 100))

然后我将Monthly_Gain_%用作颜色变量。

dat %>% ggplot(aes(Desired_Income/1000, Account_Size/1000, color = `Monthly_Gain_%`)) +
    geom_point() +
    geom_line() +
    xlab("Desired Income in Thousand Dollars") +
    ylab("Required Account Size in Thousand Dollars") + 
    ggtitle("3% to 5% per month account growth") + 
    labs(col = "Monthly Gain") +
    theme(plot.title = element_text(hjust=0.5))

enter image description here

scale_color_manual()也可以使用,但根据您的需要,可能需要对颜色进行更多修改。例如,获取:

enter image description here

您将加载RColorBrewer并使用:

library(RColorBrewer)

dat %>% ggplot(aes(Desired_Income/1000, Account_Size/1000, color = Monthly_Gain)) +
    geom_point() +
    geom_line() +
    xlab("Desired Income in Thousand Dollars") +
    ylab("Required Account Size in Thousand Dollars") + 
    ggtitle("3% to 5% per month account growth") + 
    labs(col = "Monthly Gain") +
    theme(plot.title = element_text(hjust=0.5)) + 
    scale_color_manual(labels = perc_title, values = brewer.pal(8, "Spectral"))

如果您只是想使用上面的默认颜色,请改用scale_color_discrete()scale_color_hue()也可以):

dat %>% ggplot(aes(Desired_Income/1000, Account_Size/1000, color = Monthly_Gain)) +
    geom_point() +
    geom_line() +
    xlab("Desired Income in Thousand Dollars") +
    ylab("Required Account Size in Thousand Dollars") + 
    ggtitle("3% to 5% per month account growth") + 
    labs(col = "Monthly Gain") +
    theme(plot.title = element_text(hjust=0.5)) + 
    scale_color_discrete(labels = perc_title)

enter image description here