简体   繁体   中英

R: change bar labels in geom_bar

Below is my data:

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)

And my resulted plot: 在此处输入图像描述

I would like to change the bar names to Windows , MacOS , HTML5 . How do I configure that with ggplot ? (Note that I can't change the original data)

Just give the new labels to your x variable

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)

Created on 2019-11-10 by the reprex package (v0.3.0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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