User94
User94

Reputation: 89

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. 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. 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

Upvotes: 1

Views: 2412

Answers (1)

Julius Vainora
Julius Vainora

Reputation: 48241

It seems that the number variable corresponds to the counts of 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)

enter image description here

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)

enter image description here

Upvotes: 1

Related Questions