R:忽视未知的美学:标签

时间:2018-02-13 17:01:12

标签: r

我在用geom_point制作情节时遇到错误。

library(ggplot2)
theme_set(theme_bw())

mtcars$`car name` <- rownames(mtcars) 
mtcars$mpg_z <- round((mtcars$mpg - mean(mtcars$mpg))/sd(mtcars$mpg), 2)  
mtcars$mpg_type <- ifelse(mtcars$mpg_z < 0, "below", "above") 
mtcars <- mtcars[order(mtcars$mpg_z), ]  # sort
mtcars$`car name` <- factor(mtcars$`car name`, levels = mtcars$`car name`) 

ggplot() + 
  geom_point(data=mtcars, aes(x=`car name`, y=mpg_z,label=mpg_z), stat='identity', fill="black", size=6)  +
  geom_text(color="white", size=2) +
  labs(title="Diverging Lollipop Chart", 
       subtitle="Normalized mileage from 'mtcars': Lollipop") + 
  ylim(-2.5, 2.5) +
  coord_flip() 

但我无法将数字放入点内并出现错误:

Warning: Ignoring unknown aesthetics: label

情节就在这里。先感谢您!!! enter image description here

2 个答案:

答案 0 :(得分:2)

只需将aes来电转移到ggplot

即可
ggplot(data=mtcars, aes(x=`car name`, y=mpg_z,label=mpg_z)) + 
  geom_point(stat='identity', fill="black", size=6)  +
  geom_text(color="white", size=2) +
  labs(title="Diverging Lollipop Chart", 
       subtitle="Normalized mileage from 'mtcars': Lollipop") + 
  ylim(-2.5, 2.5) +
  coord_flip() 

geom_pointgeom_text将继承相关的美学。

答案 1 :(得分:1)

这是一种不同的方式,我个人觉得这更有吸引力(它也避免了附近点的重叠标签问题):

library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 3.4.3
library(ggrepel)
#> Warning: package 'ggrepel' was built under R version 3.4.2
theme_set(theme_bw())

mtcars$`car name` <- rownames(mtcars)
mtcars$mpg_z <-
  round((mtcars$mpg - mean(mtcars$mpg)) / sd(mtcars$mpg), 2)
mtcars$mpg_type <- ifelse(mtcars$mpg_z < 0, "below", "above")
mtcars <- mtcars[order(mtcars$mpg_z),]  # sort
mtcars$`car name` <-
  factor(mtcars$`car name`, levels = mtcars$`car name`)

ggplot() +
  geom_point(
    data = mtcars,
    mapping = aes(x = `car name`, y = mpg_z),
    stat = 'identity',
    fill = "black",
    size = 6
  )  +
  geom_text(color = "white", size = 2) +
  labs(title = "Diverging Lollipop Chart",
       subtitle = "Normalized mileage from 'mtcars': Lollipop") +
  ylim(-2.5, 2.5) +
  coord_flip() +
  ggrepel::geom_label_repel(data = mtcars,
                            mapping = aes(x = `car name`, y = mpg_z, label = mpg_z))

reprex package创建于2018-02-13(v0.1.1.9000)。