【问题标题】:plot values and histogram of multiple data绘制多个数据的值和直方图
【发布时间】:2014-05-27 10:11:34
【问题描述】:

对于我想要的多个(这里:两个)值列表

  • 将值作为线或点绘制到一张图中
  • 将直方图绘制到另一个图表中并
  • 为各自的线图和直方图分配相同的颜色

我使用 ggplot2 提出了两个示例的组合,它仍然使用不同的颜色来绘制线图和直方图。也可能有点多余,创建

如何使线图和直方图的颜色相同?
奖励:如何缩短使用过的源代码?

到目前为止我的结果:

源代码(R):

# input data lists
vals_x <- c(4, 3, 6, 7, 4, 6, 9, 3, 0, 8, 3, 7, 7, 5, 9, 0)
vals_y <- c(6, 6, 4, 8, 0, 3, 7, 3, 1, 8, 2, 1, 2, 3, 6, 5)

# ------------------------------------------------
library(ggplot2)
library(gridExtra)

# prepare data for plotting
df <- rbind( data.frame( fill = "blue", obs = vals_x),
             data.frame( fill = "red",  obs = vals_y))
test_data <- data.frame(
var0 = vals_x,
var1 = vals_y,
idx  = seq(length(vals_x)))

stacked <- with(test_data,
                data.frame(value = c(var0, var1),
                           variable = factor(rep(c("Values x","Values y"),
                                                 each = NROW(test_data))),
                           idx = rep(idx, 2),
                           fill_col = c( rep("blue", length(vals_x)), 
                                         rep("red",  length(vals_y)))))

# plot line
p_line <- ggplot(stacked, aes(idx, value, colour = variable)) + 
geom_line()

# plot histogram
p_hist <- ggplot( df, aes(x=obs, fill = fill)) +
                geom_histogram(binwidth=2, colour="black", position="dodge") +
                scale_fill_identity()

# arrange diagrams
grid.arrange( p_line, p_hist, ncol = 2)

【问题讨论】:

    标签: r ggplot2 histogram


    【解决方案1】:

    最简单的方法是

    1. 在每个ggplot 对象中使用相同的数据集
    2. 然后使用scale_*_manual(或其他一些scale 呼叫)。

    所以

    ## Particularly awful colours
    p_hist = ggplot(stacked, aes(x=value, fill=variable)) + 
      geom_histogram(binwidth=2, colour="black", position="dodge") + 
      scale_fill_manual(values=c("red", "yellow"))
    
    p_line = ggplot(stacked, aes(idx, value, colour = variable)) + 
      geom_line() + 
      scale_colour_manual(values=c("red", "yellow"))
    

    顺便说一句,我不会在这里使用直方图;箱线图或密度图会更好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-21
      • 2021-04-16
      • 2019-09-12
      • 2019-04-09
      • 1970-01-01
      • 2013-11-26
      • 2019-09-19
      • 1970-01-01
      相关资源
      最近更新 更多