簡體   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))

我的代碼是

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給我這個錯誤代碼:“離散值提供給連續刻度”。 我無法弄清楚為什么未在代碼中寫出翻轉的y軸(“作者”)。

你能弄清楚嗎?

預先感謝,C。

問題是author不是連續的 ,而是離散的 因此,在下面的更新代碼中使用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

如果使用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")

再一次,如果您想指定limits()breaks它可能不值得。 無論如何,我希望這會有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM