首页 > 解决方案 > 如何更改ggplot中的轴标签?

问题描述

我在 R 中创建了一个直方图。目前,数字 1 - 8 写在 x 轴上(每个数字都有一个条形图)。我想将数字更改为风向,例如,应该站在“西”而不是 1。我试过了:

scale_x_discrete(labels=c("1" = "North", "2" = "North East", "3" = "East", "4"= "South East", "5"= "South", "6"="South West", "7"="West", "8"="North West"))

但不工作。我也试过:

scale_x_discrete(breaks=c("1","2","3", "4", "5", "6", "7", "8"), labels=c("North", "North East", "East", "South East", "South", "South West", "West", "North West"))

这是我的脚本:

options(stringsAsFactors = FALSE)

input1 <- "C:\\Users\\wind_direction.csv"

wind_direction <- read.csv(input1, sep=";")
library(ggplot2)

p3 <- ggplot(wind_direction, aes(x=winddirection)) + 
  geom_bar(color="black", fill="grey", width=0.9)+ 
  theme_bw() +
  scale_y_continuous(limits = c(0, 55), breaks = seq(0,55,10),expand=c(0,0)) +
  scale_x_discrete(labels = c("1" = "North", "2" = "North East", "3" = "East", "4"= "South East", "5"= "South", "6"="South West", "7"="West", "8"="North West"))

print(p3)

这是我的数据示例:

head(wind_direction)
         day     time winddirection
1 31.07.2018 12:51:57             3
2 31.07.2018 12:55:16             3
3 31.07.2018 12:56:29             3
4 31.07.2018 13:25:05             3
5 31.07.2018 13:36:54             3
6 31.07.2018 13:55:37             3

我的直方图现在看起来像这样

标签: rggplot2

解决方案


我认为你的代码做得很好,一个快速的解决方案只需aes(x=winddirection)要用aes(x=as.character(winddirection))or替换aes(x=as.factor(winddirection))

因此,winddirection当您将其映射到x.

只要确保你有正确的标签。您在问题中提到 1 应该是西,但在scale_x_discrete您声明 1 是北。


推荐阅读