简体   繁体   English

R:更改 geom_bar 中的条形标签

[英]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:我的结果是 plot: 在此处输入图像描述

I would like to change the bar names to Windows , MacOS , HTML5 .我想将酒吧名称更改为WindowsMacOSHTML5 How do I configure that with ggplot ?如何使用ggplot进行配置? (Note that I can't change the original data) (注意我不能更改原始数据)

Just give the new labels to your x variable只需将新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)

Created on 2019-11-10 by the reprex package (v0.3.0)代表 package (v0.3.0) 于 2019 年 11 月 10 日创建

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

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