【问题标题】:scale_colour_discrete doesn't work when reproducing an example in R cookbook复制 R 食谱中的示例时 scale_colour_discrete 不起作用
【发布时间】:2020-12-16 03:37:28
【问题描述】:

我试图在R Cookbook 复制一个示例,该示例在图例中指定颜色和形状。

原代码是

# A different data set
df2 <- data.frame(
  sex = factor(c("Female","Female","Male","Male")),
  time = factor(rep(c(1,2),2), levels=c(1,2)),
  total_bill = c(13.53, 16.81, 16.24, 17.42)
)

# A basic graph
ggplot(data=df2, aes(x=time, y=total_bill, group=sex, shape=sex)) + 
  geom_line() + 
  geom_point() +
  scale_colour_discrete(name  ="Payer",
                          breaks=c("Female", "Male"),
                          labels=c("Woman", "Man")) +
  scale_shape_discrete(name  ="Payer",
                       breaks=c("Female", "Male"),
                       labels=c("Woman", "Man"))

我不想要这条线,所以我注释掉了geom_line()+ 部分。点不再有颜色。有人可以帮忙吗?

# A different data set
df2 <- data.frame(
  sex = factor(c("Female","Female","Male","Male")),
  time = factor(rep(c(1,2),2), levels=c(1,2)),
  total_bill = c(13.53, 16.81, 16.24, 17.42)
)

# A basic graph
ggplot(data=df2, aes(x=time, y=total_bill, group=sex, shape=sex)) + 
#  geom_line() + 
  geom_point() +
  scale_colour_discrete(name  ="Payer",
                          breaks=c("Female", "Male"),
                          labels=c("Woman", "Man")) +
  scale_shape_discrete(name  ="Payer",
                       breaks=c("Female", "Male"),
                       labels=c("Woman", "Man"))

【问题讨论】:

  • 您的代码中似乎缺少colour 美学,因此这两个版本都不应首先具有颜色。

标签: r ggplot2 data-visualization


【解决方案1】:

您的两个代码块都缺少colour 美学,这将需要根据分类变量为您的几何图形着色。

您还可以简化代码:使用colour 美学或删除线条几何形状使group 美学变得多余:

# A different data set
df2 <- data.frame(
  sex = factor(c("Female","Female","Male","Male")),
  time = factor(rep(c(1,2),2), levels=c(1,2)),
  total_bill = c(13.53, 16.81, 16.24, 17.42)
)
library(ggplot2)
# A basic graph
ggplot(data=df2, aes(x=time, y=total_bill, shape=sex, colour=sex)) + 
  # geom_line() + 
  geom_point() +
  scale_colour_discrete(name  ="Payer",
                        breaks=c("Female", "Male"),
                        labels=c("Woman", "Man")) +
  scale_shape_discrete(name  ="Payer",
                       breaks=c("Female", "Male"),
                       labels=c("Woman", "Man"))

reprex package (v0.3.0) 于 2020 年 12 月 16 日创建

【讨论】:

  • 行得通,谢谢!当 x 轴的标签太多时,您是否知道如何删除它们?在此示例中,我尝试了 + scale_x_discrete(labels= c(NA,2)) ,但它只显示单词 NA。
  • 您可以尝试使用空字符串,如下所示:scale_x_discrete(labels = c("", 2)) 但是,使用 ggplot2 具有的内置选项可能是一个更可靠的解决方案,例如,请参阅guide_axis() 提供的新选项:tidyverse.org/blog/2020/03/ggplot2-3-3-0/#rewrite-of-axis-code
猜你喜欢
  • 1970-01-01
  • 2015-07-19
  • 2013-09-16
  • 2013-11-20
  • 1970-01-01
  • 2023-04-05
  • 1970-01-01
  • 2021-11-01
  • 1970-01-01
相关资源
最近更新 更多