简体   繁体   English

在 ggplot 中缩放直方图的 y 轴

[英]Scaling the y-axis of a histogram in ggplot

I am creating a histogram in R, but I have problems with the y-axis scale: The x-axis is the wind speed and the y-axis is the count of the speed.我在 R 中创建了一个直方图,但我在 y 轴刻度上有问题:x 轴是风速,y 轴是速度的计数。 The speed reaches values up to 18, but R stops the axis up to 7. Although I tried scale_y_continuous, I can't change the scale of the y-axis.速度最高可达 18,但 R 将轴停在 7。虽然我尝试了 scale_y_continuous,但我无法更改 y 轴的比例。 Can someone help me?有人能帮我吗?

This is my code:这是我的代码:

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)

This is my data:这是我的数据:

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

It seems that the number variable corresponds to the counts of speed .似乎number变量对应于speed的计数。 In that case you could do在那种情况下,你可以做

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)

在此处输入图片说明

On the other hand, perhaps what you want is actually a bar plot with specified heights rather than a histogram, in which case we have另一方面,也许您想要的实际上是具有指定高度的条形图而不是直方图,在这种情况下,我们有

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)

在此处输入图片说明

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

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