我试图用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))
如何将每个条形图集中到相应的x值?
修改2017-05-29
由于下载链接将来可能会中断,因此以下是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))
答案 0 :(得分:5)
只需删除breaks
参数,该参数多余/与binwidth
和origin
参数冲突:
# 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))
答案 1 :(得分:3)
Michael Kuhn's answer of Dec 2015现在正在发出警告:
origin
已弃用。请改用boundary
。
根据the release notes of version 2.1.0 of ggplot2
:
您现在可以指定边界(即左侧或右侧的位置)或箱的中心。原因已被弃用,支持这些论点。
因此,对于ggplot2
版本2.1.0及更高版本,建议的前进方法是使用 boundary
参数:
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代码中的一个小缺陷,该代码在Temp$Score
来电aes()
而不是ggplot(data=Temp, aes(Temp$Score))
中使用ggplot(data = Temp, aes(Score))
。
由于下载链接将来可能会中断,以下是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))