R:更改geom_bar中的栏标签

时间:2019-11-11 07:05:52

标签: r ggplot2 geom-bar

以下是我的数据:

library(ggplot2)  
myData <- data.frame(
  x = c("windows", "macos", "html5"),
  y = c(15, 56, 34)
)


ggplot(myData, aes(x=x, y=y)) + 
  geom_bar(stat="identity", width = 0.5)

我得到的剧情: enter image description here

我想将条形码名称更改为WindowsMacOSHTML5。如何使用ggplot进行配置? (请注意,我无法更改原始数据)

1 个答案:

答案 0 :(得分:1)

只需将新的labels赋予您的x变量

library(tidyverse)  

ggplot(myData, aes(x = fct_reorder(x, -y), y = y)) + 
  geom_col(width = 0.5) +
  scale_x_discrete(breaks = c("windows", "macos", "html5"),
                   labels = c("Windows", "MacOS", "HTML5"))

# or 
my_x_labels <- setNames(c("Windows", "MacOS", "HTML5"),
                        c("windows", "macos", "html5"))
ggplot(myData, aes(x = fct_reorder(x, -y), y = y)) + 
  geom_col(width = 0.5) +
  scale_x_discrete(labels = my_x_labels) +
  theme_minimal()

# or
myData <- myData %>% 
  mutate(x = factor(x, 
                    levels = c("windows", "macos", "html5"),
                    labels = c("Windows", "MacOS", "HTML5")))

ggplot(myData, aes(x = fct_reorder(x, -y), y = y)) + 
  geom_col(width = 0.5)

reprex package(v0.3.0)于2019-11-10创建