Home > Enterprise >  geom_histogram moves the histogram
geom_histogram moves the histogram

Time:10-05

I am trying to make some histograms with the library ggplot2 but they look as if the bars of the histograms don't match the 'x' axis. They look displaced as if the axis where just a little bit to the right.

As you can see the bars are displaced

As Jake From Stat Farm says in this post: ggplot histogram is not in the correct position with respect the axis I tried writing boundary=0. I also tried making some changes to binwidth and to bins in order to adapt the width of the bars to the longitude of the axis, but it didn't solve the problem.

directori_fitxers<-"C:/Users/usuari/Documents/CityLights/Data"
setwd(directori_fitxers)
library(ggplot2)

ciutat <- list.dirs(path = ".", full.names = TRUE, recursive = TRUE)
ciutat <- ciutat[-1] # Remove the first directory



for(j in 1:length(ciutat)){
  
  setwd(directori_fitxers) #Changing (setting) our working directory
  setwd(ciutat[j])
  temp = list.files(pattern="*.csv") #Read all csv files
  
  for(i in 1:length(temp)){
    taula<-read.table(temp[i],sep=";", header=T)
    taula.df<-data.frame(taula)
    taula.df
    vector<- taula.df$grid_code
    vector_big_numbers<-subset(vector,vector>100)
    if(length(vector_big_numbers)>0){
      setwd("C:/Users/usuari/Documents/CityLights/NewAnalysis/histogrames")
      vector_big_numbers<-data.frame(vector_big_numbers)
      ggplot(vector_big_numbers,aes(vector_big_numbers)) 
        geom_histogram(fill="lightblue",color="red",binwidth =20,bins=30) 
        labs(title=paste("Histograma de" ,substring(ciutat[j],9),
                        "en l'any",substring(temp[i],6,9)),boundary=0) 
        scale_x_continuous(name="Índex de lluminositat", limits=c(100, 500))
      #To save the file we can use this function in ggplot2
      ggsave(filename=paste("plot",substring(temp[i],6,9),substring(ciutat[j],9),".jpeg"),
             width = 5.73,height = 4.39)
      setwd(directori_fitxers) #initialize
      setwd(ciutat[j])
    }
  }
}



CodePudding user response:

Does this help you?

library(ggplot2)

ggplot(iris, aes(Sepal.Length))  
  geom_histogram(bins = 3)  
  scale_x_continuous(expand = c(0, 0))  
  scale_y_continuous(expand = c(0, 0))

Created on 2021-09-30 by the reprex package (v2.0.1)

Or by manual setting the bin breaks:

library(ggplot2)
library(magrittr)

breaks <- c(0, 5, 6, 10)

ggplot(iris, aes(Sepal.Length))  
  geom_histogram(breaks = breaks)  
  scale_x_continuous(expand = c(0, 0))  
  scale_y_continuous(expand = c(0, 0))

iris$Sepal.Length %>% cut(breaks = breaks) %>% table()
#> .
#>  (0,5]  (5,6] (6,10] 
#>     32     57     61

Created on 2021-09-30 by the reprex package (v2.0.1)

  • Related