简体   繁体   English

为什么ggplot2 / R中未标记x轴(翻转的y轴)?

[英]Why is the x-axis (flipped y-axis) not labeled in ggplot2/R?

# Load data
d <– structure(list(author = structure(c(1L, 2L, 4L, 3L, 5L, 6L, 8L,11L, 13L, 12L, 10L,
           9L, 7L), .Label = c("Bahr et al", "Fuller et al","Garbossa et al", 
           "Gokhale et al", "Iuchi et al", "Lee et al","Lee Y et all", "Merrel et al", 
           "Newton et al", "Rossetti et al", "Usery et al", "Wychowski et al", 
           "Zachenhofer et al"), class = "factor"),nAE = c(22L, 34L, 158L, 90L, 70L, 
           41L, 48L, 32L, 73L, 23L,25L, 13L, 46L), AE = c(3L, 1L, 7L, 1L, 3L, 10L, 3L, 
           6L, 3L,5L, 4L, 6L, 5L), SAE = c(0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L,2L, 0L, 2L, 
           0L, 0L)), .Names = c("author", "nAE", "AE", "SAE"), class = "data.frame", 
           row.names = c(NA, -13L))

My code is 我的代码是

library(dplyr)
library(tidyr)
library(ggplot2)

categories <- c("Adverse Effect", "No adverse effects", "Severe side effects")
cols <- c("#f6766d", "#01bfc4", "orange")

q <- d %>% 
  gather(key, value, -author) %>% 
  ggplot(aes(author, value, fill = key)) +
  geom_col(alpha=0.9) + 
  coord_flip() +
  scale_x_continuous(name="Author") +
  scale_y_continuous(name="Number of observations", limits=c(0, 170), 
  seq(0,170,by=10)) +
  theme_grey() +
  theme(legend.position = "top") +
  scale_fill_manual(labels = categories, values = cols) + 
  labs(fill = "")

q

R is giving me this error code: "Discrete value supplied to continuous scale" when I run the attached code. 当我运行所附的代码时,R给我这个错误代码:“离散值提供给连续刻度”。 I can't figure out why the flipped y-axis is not labeled at written in the code ("Author"). 我无法弄清楚为什么未在代码中写出翻转的y轴(“作者”)。

Can you figure it out? 你能弄清楚吗?

Thanks in advance, C. 预先感谢,C。

The issue is that author is not continuous , but discrete . 问题是author不是连续的 ,而是离散的 Hence the use of scale_x_discrete() in the updated code below, 因此,在下面的更新代码中使用scale_x_discrete()

  d %>% 
  gather(key, value, -author) %>% 
  ggplot(aes(author, value, fill = key)) +
  geom_col(alpha=0.9) + 
  coord_flip() +
  scale_x_discrete(name="Author") + # Here! scale_x_discrete()
  scale_y_continuous(name="Number of observations", limits=c(0, 170), 
  seq(0,170,by=10)) +
  theme_grey() +
  theme(legend.position = "top") +
  scale_fill_manual(labels = categories, values = cols)

ggpppp

might be clearer if you use labs() 如果使用labs()可能会更清晰

d %>% 
   gather(key, value, -author) %>% 
   ggplot(aes(author, value, fill = key)) +
   geom_col(alpha=0.9) + 
   coord_flip() +
   theme(legend.position = "top") + 
   scale_fill_manual(labels = categories, values = cols) +
   labs(y = "Number of observations", x = "Author")

then again if you want to specify limits() and breaks it might not be worth it. 再一次,如果您想指定limits()breaks它可能不值得。 Regardless, I hope this is helpful. 无论如何,我希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM