我试图解决两个问题:
以下代码是我尝试解决这两个问题。它使用coord_cartesian
解决了第一个问题,因为条形图从图形的顶部开始运行。但它并没有解决第二个问题。条形图的值位于条形图的顶部而不是底部。我认为vjust =“bottom”或0会做到这一点,但我已经在各种地方尝试过但没有成功。
library(ggplot2)
library(data.table)
dt <- data.table(
scenario = c("2010", "SSP2-NoCC", "SSP2-HGEM", "SSP1-NoCC", "SSP3-NoCC", "2010", "SSP2-NoCC", "SSP2-HGEM", "SSP1-NoCC", "SSP3-NoCC", "2010", "SSP2-NoCC", "SSP2-HGEM", "SSP1-NoCC", "SSP3-NoCC", "2010", "SSP2-NoCC", "SSP2-HGEM", "SSP1-NoCC", "SSP3-NoCC"),
value = c(45.75, 15.74, 17.16, 10.73, 24.03, 15.37, 6.87, 7.61, 5.63, 8.87, 9, 3.43, 3.76, 2.93, 4.01, 2.53, 1.79, 1.95, 1.77, 1.79),
region_name = c("Low", "Low", "Low", "Low", "Low", "Lower middle", "Lower middle", "Lower middle", "Lower middle", "Lower middle", "Upper middle", "Upper middle", "Upper middle", "Upper middle", "Upper middle", "High", "High", "High", "High", "High")
)
yLab <- "(percent)"
yRange <- c(0, 40)
plotTitle <-"Food Budget Share Of Per Capita Income"
colorList <- c("#000000", "#FEF0D9", "#2CA25F", "#FC8D59", "#D7301F")
ggplot(data = dt, aes(x = factor(region_name), y = value, group = scenario)) +
geom_col(aes(fill = scenario), position = "dodge", color = "black") +
coord_cartesian(ylim = yRange) +
theme(legend.position = "none") +
labs(x = NULL, y = yLab) +
theme(axis.text.x = element_text(angle = 45, hjust = 1, family = "Times", face = "plain")) +
theme(axis.title.y = element_text(family = "Times", face = "plain")) +
geom_text(aes(label = value, vjust = "bottom"), position = position_dodge(0.9), size = 3, angle = 90, color = "white") +
scale_fill_manual(values = colorList) +
theme(plot.title = element_text(hjust = 0.5, size = 11, family = "Times", face = "plain")) +
ggtitle(plotTitle)
答案 0 :(得分:2)
第二个问题的诀窍是将y
美学映射到固定值。我使用y = 1.25
,但您可以随意调整。我也使用size = 2.25
,因为在我看来它看起来更好。而不是vjust = 'bottom'
,请使用hjust = 'left'
,因为您正在以90度旋转应用这些设置。所以geom_text
部分应该是
geom_text(data = dt, aes(x = factor(region_name), y=0.5, label = round(value, 1)), position = position_dodge(0.9), size = 2.25, angle = 90, color = "white", hjust = 'left')
答案 1 :(得分:0)
设置绘图限制和允许栏超出
您可以使用coord_cartesian
设置绘图的限制。与scale_y_continuous
不同,这可以让数据扩展到图表限制之外。所以coord_cartesian(ylim = c(0, 30))
标签栏
与其他答案类似,但您可以在ifelse
中使用geom_text
语句,只显示标签中的标签,这些标签足以让标签适合。
示例代码
ggplot(data = dt, aes(x = factor(region_name), y = value, group = scenario)) +
geom_col(aes(fill = scenario), position = "dodge", color = "black") +
coord_cartesian(ylim = c(0, 30)) +
theme(legend.position = "none") +
labs(x = NULL, y = yLab) +
theme(axis.text.x = element_text(angle = 45, hjust = 1, family = "Times", face = "plain")) +
theme(axis.title.y = element_text(family = "Times", face = "plain")) +
scale_fill_manual(values = colorList) +
theme(plot.title = element_text(hjust = 0.5, size = 11, family = "Times", face = "plain")) +
ggtitle(plotTitle) +
geom_text(data = dt, aes(x = factor(region_name),
y=0.5, label = ifelse(value < 3, "", round(value, 1))),
position = position_dodge(0.9),
size = 2.25,
angle = 90,
color = "white",
hjust = 'left')