【问题标题】:How to add legends in this context?如何在这种情况下添加图例?
【发布时间】:2020-04-17 15:54:22
【问题描述】:


songs %>% group_by(year) %>% summarise(count=nth(pop,1))%>%
  ggplot(aes(x=factor(year),y=count,fill=year))+geom_bar(stat ='identity' )+theme_classic()

1.如何调整我的图例以显示年份(2010:2019)而不是现在显示的内容? 2.Scale_size_manual 不起作用。

【问题讨论】:

  • 由于您将year 映射到fill,因此您需要scale_fill_manual() 而不是scale_size_manual()。如果year 应该是离散的而不是数字,则可以使用fill = factor(year)
  • @aosmith Aesthetics 必须是长度为 1 或相同的长度,因此它不起作用!!
  • 如果您继续使用数字 fill,您可能需要 scale_fill_gradient()breaks。您应该将您尝试过的代码以及错误添加到您的问题中,以便人们可以看到您的代码如何“不起作用”。有一个可重复的例子也将有所帮助;不知道songs从哪里来,可能是建立在billboard数据集上的吧?

标签: r ggplot2 visualization kaggle


【解决方案1】:

您需要每次(或在外部)将year 设置为一个因素,而不仅仅是一次。我没有你的数据,所以我会使用mtcars

library(ggplot2)
library(dplyr)

# first plot
mtcars %>%
  ggplot(aes(factor(carb), disp, fill=carb)) +
  geom_bar(stat="identity")

# second plot
mutate(mtcars, carb = factor(carb)) %>%
  ggplot(aes(carb, disp, fill=carb)) +
  geom_bar(stat="identity")

# alternate code for second plot, not shown
mtcars %>%
  ggplot(aes(factor(carb), disp, fill=factor(carb))) +
  # both     ^^^^^^        and        ^^^^^^
  geom_bar(stat="identity")

(有很多方法可以转换为因子。我在这里使用dplyr,但可以很容易地在base 或data.table 中完成。)

我在上面包含了“替代”代码,它显示了将手册 factor 应用于 carb 的每次使用;在我看来,这不是首选方法,因为如果您要多次执行此操作,只需在绘图前执行一次并多次使用即可。如果您需要序号year 和数字版本,您可以添加一个新字段,例如ordinal_year=factor(year)

【讨论】:

    猜你喜欢
    • 2021-08-17
    • 1970-01-01
    • 2021-02-13
    • 2020-03-02
    • 1970-01-01
    • 2022-01-17
    • 2023-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多