altering the color of one value in a ggplot histogram

試著忘記壹切 提交于 2021-02-07 10:50:36

问题


I have a simplified dataframe

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")

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:


1) To draw bins in different colors you can use geom_histogram() for subsets.

2) To center bars along numbers on the x axis you can invoke scale_x_continuous(breaks=..., labels=...)

So, this code

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)

produces the plot:

enter image description here




回答2:


You can do this with a single geom_histogram() by using aes(fill = cond).

To choose different colours, use one of the scale_fill_*() functions, e.g. scale_fill_manual(values = c("red", "blue").

library(ggplot2)
df <- data.frame(wins=c(1,1,3,1,1,2,11,2,11,15,1,1,3))
df$cond <- df$wins == tail(df,1)$wins
ggplot(df, aes(x=wins, fill = cond)) +
  geom_histogram() +
  scale_x_continuous(breaks=df$wins+0.25, labels=df$wins) +
  scale_fill_manual(values = c("red", "blue"))



来源:https://stackoverflow.com/questions/13372523/altering-the-color-of-one-value-in-a-ggplot-histogram

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!