geom_histogram 移动直方图
Posted
技术标签:
【中文标题】geom_histogram 移动直方图【英文标题】:geom_histogram moves the histogram 【发布时间】:2021-11-22 05:41:11 【问题描述】:我正在尝试使用库 ggplot2 制作一些直方图,但它们看起来好像直方图的条形与“x”轴不匹配。它们看起来好像轴稍微向右移动了一点。
As you can see the bars are displaced
正如来自 Stat Farm 的杰克在这篇文章中所说:ggplot histogram is not in the correct position with respect the axis 我试着写边界 = 0。我还尝试对 binwidth 和 bin 进行一些更改,以使条形的宽度适应轴的经度,但这并没有解决问题。
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])
【问题讨论】:
如果您可以制作一个最小的可重现问题示例,将会很有帮助。 r 包reprex
可以快速发布代码,包括结果。例如,在上面的代码中,for 循环会分散问题的注意力。
【参考方案1】:
这对你有帮助吗?
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 创建于 2021-09-30 (v2.0.1)
或者通过手动设置分档:
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 创建于 2021-09-30 (v2.0.1)
【讨论】:
非常感谢danlooo,等我回去工作我会回复你的。以上是关于geom_histogram 移动直方图的主要内容,如果未能解决你的问题,请参考以下文章
R geom_histogram position="identity" 不一致
R语言 柱状图 geom_col 与 geom_bar 与geom_histogram(直方图)