使用填充参数覆盖直方图

时间:2018-11-04 19:52:41

标签: r ggplot2 histogram fill

我想创建一个图形来显示每种事件多久减少一次物种。

我总共有9种和8个事件。我想修复诸如不同条形组(填充)和x轴上的物种之类的事件,如下图所示。

我创建了以下脚本,但收到此错误消息

  

错误:StatBin需要连续的x变量,而x变量是离散的。也许您想要stat =“ count”?

有人会对如何编写正确的脚本有任何建议吗? 预先非常感谢

library(ggplot2)
event <- factor(Dataset, levels = c("A", "B", "C", "D", "E", "F", "G",  "H"))
ggplot(Dataset) +
  geom_histogram(aes(x=specie, fill=event), 
                 colour="grey50", alpha=0.5, position="identity")

数据

Dataset <- structure(list(specie = structure(1:9, .Label = c("Hipp_amph", 
"Hipp_eq", "Phil_mont", "Pota_larv", "Red_aru", "Sylv_grim", 
"Sync_caf", "Trag_oryx", "Trag_scri"), class = "factor"), A = c(2.97029703, 
0, 13.86138614, 12.87128713, 0, 17.82178218, 2.97029703, 0, 0.99009901
), B = c(0, 7.920792079, 55.44554455, 51.48514851, 33.66336634, 
27.72277228, 33.66336634, 15.84158416, 62.37623762), C = c(0, 
5.940594059, 0.99009901, 8.910891089, 2.97029703, 0, 10.89108911, 
4.95049505, 21.78217822), D = c(0, 0, 0, 0.99009901, 0, 0, 0, 
0, 0), E = c(16.83168317, 28.71287129, 74.25742574, 100, 40.59405941, 
32.67326733, 89.10891089, 27.72277228, 86.13861386), F = c(6.930693069, 
0, 10.89108911, 42.57425743, 0, 0, 7.920792079, 0, 2.97029703
), G = c(0, 0, 0, 0.99009901, 0, 0, 0, 0, 0), H = c(0, 4.95049505, 
1.98019802, 1.98019802, 15.84158416, 0, 19.8019802, 0, 1.98019802
)), .Names = c("specie", "A", "B", "C", "D", "E", "F", "G", "H"
), class = "data.frame", row.names = c(NA, -9L))

enter image description here

1 个答案:

答案 0 :(得分:0)

问题确实是您要尝试将因子/字符变量传递给x轴,在这种情况下,x轴需要数字值。

您可以在数据框上尝试以下内容,并使用specie制作网格;要么这样做,要么牺牲event(A,B等)来填充小节,然后将specie放在fill中。

此外,首先需要以长格式收集数据,以便能够将其传递到aes

library(tidyverse)

Dataset <- Dataset %>% gather(event, value, 2:9)

ggplot(Dataset) + 
  geom_histogram(aes(x=value, fill=event), colour="grey50", alpha=0.5, position="identity") + 
  facet_wrap(~ specie)