r - 无法更改 ggplot2 直方图上的颜色

标签 r ggplot2 histogram

我正在使用 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 文档,我不确定我错过了什么,我感谢所有帮助,谢谢

最佳答案

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

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

生成一个灰色填充的图

enter image description here

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

生成一个红色填充的图

enter image description here

关于r - 无法更改 ggplot2 直方图上的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49354785/

相关文章:

r 使用函数内的 data.table 在子集上创建模型

r - 如何将函数另存为新的 R 脚本?

r - 使用 R 中的 ggplot 和 patchwork 更改轴标签和比例

r - 如何将覆盖其他标签的箭头发送到 geom_label_repel 的后面?

opencv - 如何训练 HOG 并使用我的 HOGDescriptor?

matlab - 3D直方图和条件着色

gnuplot - 设置透明直方图

r - 使用ggplot为 map 上不同的相邻区域着色

R - 计算每列中某些值的数量

r - ggplot2:geom_bar,计算分面百分比