r - 如何更改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
解决方案
我认为你的代码做得很好,一个快速的解决方案只需aes(x=winddirection)
要用aes(x=as.character(winddirection))
or替换aes(x=as.factor(winddirection))
。
因此,winddirection
当您将其映射到x
.
只要确保你有正确的标签。您在问题中提到 1 应该是西,但在scale_x_discrete
您声明 1 是北。
推荐阅读
- c++ - 如何在 c++ 中创建适用于windwos和linux的文件夹(目录)
- android - 使用 rxAndroid 更新所选商品的价格
- performance - Neo4j Cypher 查询优化 - APOC 手动索引关系属性
- ajax - 如何从 SharePoint Online 调用 Bamboo HR API 调用
- swift - CoreData Predicate get every sentence that contains any word in array
- php - 重定向的登录页面
- php - Display a custom button with a dynamic Product ID using a shortcode in Woocommerce
- java - Spring Boot 应用程序未启动
- javascript - 设置 li 的 JS 代码选择其孩子的值为 '100'
- jenkins - 通过 Jenkins 错误执行 Katalon 套件