我使用facet_grid制作了facet图。它看起来就像我想要的,除了y轴看起来卡在图中,数据是百分比,它来自(3%-95%)。有没有办法让它看起来更好?
plot <- ggplot(data=mydata, mapping=aes(x=year, y=value)) +
geom_bar(stat="identity", aes(color=coralType))
我试过用:
plot + facet_grid(coralType ~ location, scales="free")
和
plot + facet_grid(coralType ~ location, scales="free_x")
plot + facet_grid(coralType ~ location, scales="free_y")
我也试过ylim=c(3, 100) ylim=range(3:100)
这些都没有用。
这是我的数据:
structure(list(location = structure(c(1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("site01", "site02",
"site03", "site04", "site05", "site06", "site07", "site08"), class = "factor"),
coralType = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 2L, 2L, 2L), .Label = c("blue corals", "hard corals",
"sea fans", "sea pens", "soft corals"), class = "factor"),
longitude = c(143.515, 143.515, 143.515, 143.515, 143.515,
143.515, 143.515, 143.515, 143.515, 143.515, 143.515, 143.515,
143.515, 143.515, 143.515), latitude = c(-11.843, -11.843,
-11.843, -11.843, -11.843, -11.843, -11.843, -11.843, -11.843,
-11.843, -11.843, -11.843, -11.843, -11.843, -11.843), year = c(2010L,
2011L, 2012L, 2013L, 2014L, 2015L, 2016L, 2017L, 2011L, 2012L,
2013L, 2014L, 2015L, 2016L, 2017L), value = c(30, 30, 41,
43, 50, 54, 57, 58, 10, 11, 30, 31, 31, 32, 34)), row.names = c(NA,
15L), class = "data.frame")
随着OP提供的数据,产生的图形
ggplot(mydata) +
aes(x = year, y = value, fill = coralType) +
geom_col() +
facet_grid(coralType ~ location)
看起来很好,因为value
是数字。
请注意,使用fill
美学而不是colour
美学。此外,geom_col()
被用作geom_bar(stat = "identity")
的捷径。
当我将value
绘制为字符(由ggplot2
变成一个因子)时,我可以重现这个问题:
max_value <- 60
ggplot(mydata) +
aes(x = year, y = sprintf("%.2f %%", 100 * value / max_value),
fill = coralType) +
geom_col() +
facet_grid(coralType ~ location)
由于数据点数量有限,这并不像OP的屏幕截图那样混乱。
如果OP想要在y轴上显示百分比而不是绝对值,则scale_y_continuous(labels = scales::percent)
可以与数值一起使用:
max_value <- 60
ggplot(mydata) +
aes(x = year, y = value / max_value, fill = coralType) +
geom_col() +
facet_grid(coralType ~ location) +
scale_y_continuous(labels = scales::percent)
mydata <-
structure(list(location = structure(c(1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("site01", "site02",
"site03", "site04", "site05", "site06", "site07", "site08"), class = "factor"),
coralType = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 2L, 2L, 2L), .Label = c("blue corals", "hard corals",
"sea fans", "sea pens", "soft corals"), class = "factor"),
longitude = c(143.515, 143.515, 143.515, 143.515, 143.515,
143.515, 143.515, 143.515, 143.515, 143.515, 143.515, 143.515,
143.515, 143.515, 143.515), latitude = c(-11.843, -11.843,
-11.843, -11.843, -11.843, -11.843, -11.843, -11.843, -11.843,
-11.843, -11.843, -11.843, -11.843, -11.843, -11.843), year = c(2010L,
2011L, 2012L, 2013L, 2014L, 2015L, 2016L, 2017L, 2011L, 2012L,
2013L, 2014L, 2015L, 2016L, 2017L), value = c(30, 30, 41,
43, 50, 54, 57, 58, 10, 11, 30, 31, 31, 32, 34)), row.names = c(NA,
15L), class = "data.frame")