【问题标题】:Can't change the colors on a ggplot2 histogram无法更改 ggplot2 直方图上的颜色
【发布时间】:2018-08-27 12:43:31
【问题描述】:

我正在处理一个 5k 完成时间的数据集,看起来有点像这样:

"15:34"
"14:23"
"17:34"

等等,有很多,但它们都是这样格式化的。我能够将它们全部转换为 POSIXct,并将它们存储在数据框中,以便更轻松地使用 ggplot2,但对于我的生活,我无法让 ggplot 更改颜色。填充命令不起作用,图形只是保持灰色。

我尝试仅引用我创建的 POSIXct 对象,但 ggplot 抛出错误并告诉我它不适用于 POSIXct。我能够显示直方图的唯一方法是将其存储在数据框中。

我目前使用的代码如下:

#make the data frame
df <- data.frame(
finish_times = times_list)


#set the limits on the x axis as datetime objects
 lim <- as.POSIXct(strptime(c('2018-3-18 14:15', '2018-3-18 20:00'), format = "%Y-%m-%d %M:%S"))

#making the plot
ggplot(data = df, aes(x = finish_times)) + 
  geom_histogram(fill = 'red') + #this just doesn't work
  stat_bin(bins = 30) + 
  scale_x_datetime(labels = date_format("%M:%S"),
                   breaks = date_breaks("1 min"),
                   limits = lim) +
  labs(title = "2017 5k finishers", 
       x='Finish Times',
       y= 'Counts')

我浏览了很多 ggplot 和 R 文档,但我不确定我缺少什么,感谢所有帮助,谢谢

【问题讨论】:

  • 你确定 ggplot 代码没有抛出错误,只是留下了你最后的情节吗? fill = "red"' 应该可以工作,例如试试:ggplot() + geom_histogram(aes(x=rnorm(100)), fill = 'red')
  • 绘图包有很多不同的部分,仅从文档中很难将它们放在一起。如果您是 ggplot 新手,一个不错的起点是 r4ds.had.co.nz

标签: r ggplot2 histogram


【解决方案1】:

stat_bin(bins = 30) 覆盖您在geom_histogram() 中设置的任何内容。通常,每个几何图形都有一个关联的默认统计信息,您可以使用两者之一来绘制对象,但是当您尝试同时使用两者时,您可能会遇到问题。有几种解决方案。这是一个例子。

ggplot(diamonds, aes(x = carat)) + geom_histogram(fill = "red") + stat_bin(bins = 30)

生成带有灰色填充的图

ggplot(diamonds, aes(x = carat)) + geom_histogram(fill = "red", bins = 30)

生成一个带有红色填充的图

【讨论】:

  • 天哪,非常感谢,我一直在努力解决这个问题!
  • 不客气 :) 随意投票并接受这个答案。我想你现在可以做到了。
  • stat_bin() 在我尝试时不会覆盖颜色:ggplot() + geom_histogram(aes(x=rnorm(100)), fill = "red") + stat_bin(bins = 30)
  • 我猜那是因为您使用 aes 设置了一个映射值,因此会影响连续调用的继承方式,但您可能必须使用浏览器逐步检查才能确定
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-30
  • 2017-03-25
  • 1970-01-01
  • 2016-03-06
  • 2012-08-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多