geom_histogram 移动直方图

geom_histogram moves the histogram

我正在尝试使用库 ggplot2 制作一些直方图,但它们看起来好像直方图的条形图与 'x' 轴不匹配。它们看起来移位了,好像轴向右移动了一点点。

As you can see the bars are displaced

正如 Stat Farm 的 Jake 在这篇 post 中所说: 我试着写 boundary=0。我还尝试对 binwidth 和 bins 进行一些更改,以使条形宽度适应轴的经度,但这并没有解决问题。

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])
    }
  }
}



这对你有帮助吗?

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

reprex package (v2.0.1)

于 2021-09-30 创建

或手动设置分格:

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

reprex package (v2.0.1)

于 2021-09-30 创建