我正在R中创建直方图,但是y轴比例有问题:x轴是风速,y轴是风速的计数。速度最高可达到18,但R最多可将轴停止7。尽管我尝试过scale_y_continuous,但无法更改y轴的比例。有人能帮我吗?
这是我的代码:
options(stringsAsFactors = FALSE)
input <- "C:\\Users\speed_R.csv"
speed_R <- read.csv(input, sep=";")
library(lubridate)
library(ggplot2)
p3 <- ggplot(speed_R, aes(x=speed)) +
geom_histogram(color="black", fill="grey", breaks=seq(1, 8))+
theme_bw()+scale_y_continuous(breaks=seq(1,20,2),expand=c(0,0))+
scale_x_continuous(breaks=seq(1,8,1))
print(p3)
这是我的数据
dput(speed_R)
structure(list(number = c(1L, 2L, 7L, 4L, 1L, 3L, 2L, 1L, 5L,
6L, 4L, 1L, 7L, 1L, 18L, 6L, 2L, 1L, 15L, 8L, 9L, 5L, 10L, 1L,
13L, 3L, 9L, 5L, 8L, 11L, 4L, 1L, 2L, 15L, 2L, 3L, 4L, 2L, 3L,
3L), speed = c(1.4, 1.6, 1.8, 1.9, 2, 2.2, 2.3, 2.4, 2.5, 2.7,
2.8, 3, 3.1, 3.2, 3.3, 3.5, 3.6, 3.7, 3.8, 3.9, 4.1, 4.3, 4.4,
4.7, 4.8, 4.9, 5, 5.1, 5.2, 5.6, 5.7, 6, 6.4, 6.5, 6.6, 6.8,
6.9, 7, 7.3, 7.4)), class = "data.frame", row.names = c(NA, -40L
))
head(speed_R)
number speed
1 1 1.4
2 2 1.6
3 7 1.8
4 4 1.9
5 1 2.0
6 3 2.2
答案 0 :(得分:1)
似乎number
变量对应于speed
的计数。在这种情况下,您可以
ggplot(speed_R[rep(1:nrow(speed_R), speed_R$number), ], aes(x = speed)) +
geom_histogram(color = "black", fill = "grey", breaks = 1:8) +
theme_bw() + scale_y_continuous(expand = c(0, 0)) +
scale_x_continuous(breaks = 1:8)
另一方面,也许您想要的实际上是具有指定高度的条形图,而不是直方图,在这种情况下,我们有
ggplot(speed_R, aes(x = speed, y = number)) +
geom_col(color = "black", fill = "grey") +
theme_bw() + scale_y_continuous(expand = c(0, 0)) +
scale_x_continuous(breaks = 1:8)