R 使用ggplot2将直方图的中心条居中

R 使用ggplot2将直方图的中心条居中,r,ggplot2,R,Ggplot2,我正在尝试使用ggplot2软件包将我的条形图居中。条形图未与相应值的中心对齐,这可能会导致非专家读者产生一些误解。我的情节是这样的: 为了重现绘图,请使用以下代码: # Load data Temp <- read.csv("http://pastebin.com/raw.php?i=mpFpjqJt", header = TRUE, stringsAsFactors=FALSE, sep = ";") # Load package library(ggplot2) # Plot hi

我正在尝试使用ggplot2软件包将我的条形图居中。条形图未与相应值的中心对齐,这可能会导致非专家读者产生一些误解。我的情节是这样的:

为了重现绘图,请使用以下代码:

# Load data
Temp <- read.csv("http://pastebin.com/raw.php?i=mpFpjqJt", header = TRUE, stringsAsFactors=FALSE, sep = ";")
# Load package
library(ggplot2)
# Plot histogram using ggplot2
ggplot(data=Temp, aes(Temp$Score)) + 
geom_histogram(breaks=seq(0, 8, by =1), col="grey", aes(fill=..count..), binwidth = 1, origin = -0.5) 
+ scale_fill_gradient("Count", low = "green", high = "red") 
+ labs(title="Title") 
+ labs(x="X-Title", y="Y-Title") 
+ xlim(c(3,9))

只需删除与
binwidth
origin
参数冗余/冲突的
breaks
参数:

# Load data
Temp <- read.csv("http://pastebin.com/raw.php?i=mpFpjqJt", header = TRUE, stringsAsFactors=FALSE, sep = ";")
# Load package
library(ggplot2)
# Plot histrogram using ggplo2
ggplot(data=Temp, aes(Temp$Score)) + 
  geom_histogram(col="grey", aes(fill=..count..), binwidth = 1, origin = -0.5) + 
  scale_fill_gradient("Count", low = "green", high = "red") + 
  labs(title="Title") + 
  labs(x="X-Title", y="Y-Title") + 
  xlim(c(3,9))
#加载数据
温度现在返回警告:

origin
已弃用。请改用
边界

根据:

现在可以指定边界(即左侧或右侧的位置)或箱子的中心。为了支持这些论点,origin遭到了抨击

因此,对于
ggplot2
2.1.0版及更高版本,建议的前进方向是使用
边界
参数:

library(ggplot2)   # CRAN version 2.2.1 used
ggplot(data=Temp, aes(Score, fill = ..count..)) + 
  geom_histogram(col = "grey", binwidth = 1, boundary = 0.5) +
  scale_fill_gradient("Count", low = "green", high = "red") +
  labs(title = "Title") +
  labs(x = "X-Title", y = "Y-Title") +
  xlim(c(3, 9))
center
参数

...
geom_histogram(col = "grey", binwidth = 1, center = 0) +
...
结果是一样的:

顺便说一句:我已经删除了OP代码中的一个小缺陷,它在
aes()
call
ggplot(data=Temp,aes(Temp$Score))
中使用
Temp$Score
而不是
ggplot(data=Temp,aes(Score))

资料 由于下载链接将来可能中断,以下是通过
dput()
返回的数据:


Temp是你的分数数字吗?是的,是。正如您在这里看到的,分数值只是数字:如果没有数据,很难测试,但请尝试ggplot(data=Temp,aes(as.factor(Score))…如果分数只能取几个值,并且您希望每个值都有一个条形图,那么条形图可能比直方图更合适?@CathG:您说得对。范围仅在1到7之间,因此条形图也可能是一种合适的方法。那太好了-谢谢!这正是我要寻找的:)在ggplot2(v3.3.3)中,而不是
原点
,可以使用
中心
边界
(正如另一个答案所说)。
...
geom_histogram(col = "grey", binwidth = 1, center = 0) +
...
Temp <- structure(list(ID = 1:30, Score = c(6L, 6L, 6L, 5L, 5L, 5L, 6L, 
5L, 5L, 5L, 4L, 7L, 4L, 6L, 6L, 6L, 6L, 6L, 5L, 5L, 7L, 5L, 6L, 
5L, 5L, 5L, 4L, 6L, 6L, 5L)), .Names = c("ID", "Score"), class = "data.frame", 
row.names = c(NA, -30L))