使用ggplot2的直方图中心条 [英] Center bars of histogram using ggplot2
问题描述
我正在尝试使用ggplot2软件包将栏居中.条形图未与相应值的中心对齐,这可能会引起非专业读者的一些误解.我的情节看起来像这样:
I am trying to center my bars with the ggplot2 package. The bars are not aligned to the center of the corresponding value, which can lead to some misunderstanding for non-expert readers. My plot looks like this:
为了重现该图,请使用以下代码:
In order to reproduce the plot, please use the following code:
# 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))
如何将每个条形居中到相应的x值?
How I can center each bar to the corresponding x-value?
编辑2017-05-29 由于下载链接将来可能会中断,因此以下是 dput()
Edit 2017-05-29
As the download link may break in the future, here are the data as returned by dput()
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))
推荐答案
只需删除 breaks
参数,该参数是多余的,并且与 binwidth
和冲突来源
参数:
Just remove the breaks
argument, which is redundant / in conflict with the binwidth
and origin
arguments:
# 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))
这篇关于使用ggplot2的直方图中心条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!