我在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
答案 0 :(得分:1)
我认为您在代码方面做得很好,而快速的解决方案只是将aes(x=winddirection)
替换为aes(x=as.character(winddirection))
或aes(x=as.factor(winddirection))
。
因此,当您将winddirection
映射到x
时,只需确保它是字符或因素。
请确保您具有正确的标签。您在问题中提到1应该是西边,但是在scale_x_discrete
中您声明1是北边。