简体   繁体   English

如何更改ggplot中的轴标签?

[英]How can I change axis label in ggplot?

I created a histogram in R. At the moment, the numbers 1 - 8 are written on the x-axis (for each number a bar). 我在R中创建了一个直方图。此刻,数字1-8被写在x轴上(每个数字都是一个小节)。 I would like to change the numbers into the wind direction, eg instead of 1, there should stand "west". 我想将数字更改为风向,例如,将数字改为“ 1”而不是“ 1”。 I tried: 我试过了:

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"))

But is not working.I also tried: 但是没有用,我也尝试过:

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"))

Here is my script: 这是我的脚本:

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)

Here is a sample of my data: 这是我的数据样本:

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

我的直方图看起来像这样

I think you did a good job with your code and a fast solution involves just to replace aes(x=winddirection) with aes(x=as.character(winddirection)) or aes(x=as.factor(winddirection)) . 我觉得你的工作做得很好与您的代码和一个快速的解决方案只涉及到替代aes(x=winddirection)aes(x=as.character(winddirection))aes(x=as.factor(winddirection))

So, you just need to be sure that winddirection is character or factor when you map it into x . 因此,当您将winddirection映射到x时,只需确保winddirection是字符或因子。

Just be sure you have the right labeling. 只要确保您有正确的标签。 You mention in your question that 1 should be west, but in scale_x_discrete you declare that 1 is north. 您在问题中提到1应该是西,但是在scale_x_discrete您声明1是北。

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

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