改变ggplot直方图中一个值的颜色
问题描述:
我有一个简化的数据框
library(ggplot2)
df <- data.frame(wins=c(1,1,3,1,1,2,1,2,1,1,1,3))
ggplot(df,aes(x=wins))+geom_histogram(binwidth=0.5,fill="red")
我想获得序列3中的最终值,用不同的填充或alpha表示.识别其价值的一种方法是
I would like to get the final value in the sequence,3, shown with either a different fill or alpha. One way to identify its value is
tail(df,1)$wins
此外,我想移动直方图条,以便它们在数字上居中.我尝试从胜利值中减去失败
In addition, I would like to have the histogram bars shifted so that they are centered over the number. I tried unsuccesfully subtracting from the wins value
答
1)要绘制不同颜色的垃圾箱,可以对子集使用 geom_histogram()
.
1) To draw bins in different colors you can use geom_histogram()
for subsets.
2)要使条形图沿x轴上的数字居中,可以调用 scale_x_continuous(breaks = ...,labels = ...)
2) To center bars along numbers on the x axis you can invoke scale_x_continuous(breaks=..., labels=...)
所以,这段代码
library(ggplot2)
df <- data.frame(wins=c(1,1,3,1,1,2,11,2,11,15,1,1,3))
cond <- df$wins == tail(df,1)$wins
ggplot(df, aes(x=wins)) +
geom_histogram(data=subset(df,cond==FALSE), binwidth=0.5, fill="red") +
geom_histogram(data=subset(df,cond==TRUE), binwidth=0.5, fill="blue") +
scale_x_continuous(breaks=df$wins+0.25, labels=df$wins)
产生剧情: