我使用 ggplot 并且我想叠加两个条形图。这是我的头部数据集:(数据 = csv_total)
habitates surf_ha obs_flore obs_faune
1 Régénération de feuillus 0.4 0.0 2.4
2 Villes, villages et sites industriels 0.7 0.0 15.6
3 Forêt de feuillus 384.8 1.1 0.0
4 Forêt de Pin d'alep 2940.8 2.1 1.0
5 Maquis 45.9 2.3 0.3
6 Plantation de ligneux 306.4 2.5 1.0
这是我的 2 个条形图:
hist1 <- ggplot(csv_total, aes(x = habitates, y = obs_flore)) + geom_bar(stat = "identity") +
theme(axis.text.x= element_text(angle=50, hjust = 1))
hist2 <- ggplot(csv_total, aes(x = habitates, y = obs_faune)) + geom_bar(stat = "identity") +
theme(axis.text.x= element_text(angle=50, hjust = 1))
X 轴代表栖息地,Y 轴代表观测数量(hist1 的植物群和 hist2 的动物群)。
所以我想通过叠加两者来创建一个条形图。为了获得 X 轴上的栖息地和 Y 轴上的两种不同颜色的植物群观察和动物群观察。您是否有将这些条形图叠加在一起的想法?
Sry 我的英语不好。谢谢!
我必须为你选择,但我更喜欢第二个(虽然它可能会更长一点)。
library(ggplot2)
ggplot(csv_total) +
geom_col(aes(x = habitates, y = obs_flore, fill = "obs_flore"), alpha = 0.5) +
geom_col(aes(x = habitates, y = obs_faune, fill = "obs_faune"), alpha = 0.5) +
theme(axis.text.x = element_text(angle = 50, hjust = 1))
这看起来不错,但通过以下内容,我们不必像上面那样人为地创建填充图例,我们可以使用选项“躲避”将列并排放置。首先,我们必须将数据转换为长格式(使用gather
from tidyr
):
library(tidyr)
csv_total_long <- gather(csv_total, flore_faune, obs, obs_flore, obs_faune)
csv_total_long
# A tibble: 12 x 4
# habitates surf_ha flore_faune obs
# <chr> <dbl> <chr> <dbl>
# 1 A 0.4 obs_flore 0
# 2 B 0.7 obs_flore 0
# 3 C 385. obs_flore 1.1
# 4 D 2941. obs_flore 2.1
# 5 E 45.9 obs_flore 2.3
# 6 F 306. obs_flore 2.5
# 7 A 0.4 obs_faune 2.4
# 8 B 0.7 obs_faune 15.6
# 9 C 385. obs_faune 0
# 10 D 2941. obs_faune 1
# 11 E 45.9 obs_faune 0.3
# 12 F 306. obs_faune 1
现在我们为每个 faune 和 flore 观察增加了一行。然后我们可以绘制彼此相邻的列。如果没有position = "dodge"
.
ggplot(csv_total_long, aes(x = habitates, y = obs, fill = flore_faune)) +
geom_col(alpha = 0.5, position = "dodge") +
scale_fill_brewer(palette = "Dark2") +
theme(axis.text.x = element_text(angle = 50, hjust = 1))
我geom_col
在这里使用,因为它geom_bar
与stat = "identity"
.
数据
我使用字母表示栖息地,因为我的系统无法正确识别原始数据,这不是这里的重点。
csv_total <- structure(list(habitates = c("A", "B", "C", "D", "E", "F"),
surf_ha = c(0.4, 0.7, 384.8, 2940.8, 45.9, 306.4),
obs_flore = c(0.0, 0.0, 1.1, 2.1, 2.3, 2.5),
obs_faune = c(2.4, 15.6, 0.0, 1.0, 0.3, 1.0)),
row.names = c(NA, -6L),
class = c("tbl_df", "tbl", "data.frame"))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句