繁体   English   中英

如何使用负 y 值的 geom_bar 制作直立条?

[英]How to make upright bars using geom_bar with negative y values?

我正在尝试使用 ggplot 制作以下条形图(如果 base r 更简单那没关系,我只是更熟悉 ggplot): 目标图

这对我来说似乎很简单,但出于某种原因,无论我尝试什么,它都不起作用。

我的 df:

structure(list(Target_depth_mean1 = c(3, 4, 5, 6, 7, 8, 9, 10, 
11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22), TS_mean1 = c(-47, 
-45, -40, -43, -40, -39, -42, -42, -37, -41, -41, -38, -40, -41, 
-41, -40, -42, -42, -41, -38)), row.names = c(NA, -20L), class = c("tbl_df", 
"tbl", "data.frame"))

我尝试了以下方法:

ggplot(STmean, aes(x=Target_depth_mean1, y=TS_mean1)) +
  geom_bar(stat="identity", position = "dodge") #almost what I want but I don't want the bars upside down, also tried geom_col instead but still upside down bars

和...

ggplot(STmean, aes(x=Target_depth_mean1, y=TS_mean1)) +
  geom_bar(stat="identity", position = "dodge") +
  ylim(-48,-36) #doesn't plot anything

和...

ggplot(STmean, aes(x=Target_depth_mean1, y=TS_mean1)) +
  geom_bar(stat="identity") +
  coord_cartesian(ylim = c(-50,-30)) #still upside down bars

和...

ggplot(STmean, aes(x=Target_depth_mean1, y=TS_mean1)) +
  geom_bar(stat="identity", position = "dodge") +
  scale_y_reverse() #plots upright but I need the values reversed too (smaller on bottom)

和...

ggplot(STmean, aes(x=Target_depth_mean1, y=TS_mean1)) +
  geom_bar(stat="identity", position = "dodge") +
  scale_y_reverse(limits=c(-50,-30)) #doesn't plot anything

和...图书馆(天平)

ggplot(STmean, aes(x=Target_depth_mean1, y=TS_mean1)) +
  geom_bar(stat="identity") +
  scale_y_continuous(limits = c(-50, -30), oob= rescale_none) #still upside down, and if I switch to limits = c(-30,-50) plots upright but again need smaller values (-50) on bottom of y axis...

和...

ggplot(STmean, aes(x=Target_depth_mean1, y=TS_mean1)) +
  geom_bar(stat="identity") +
  coord_cartesian(ylim = range(STmean$TS_mean1)) #upside down!

我还尝试使 TS 值为正并在...之后添加负号

STmean1 <- STmean %>%
  mutate(across(c("TS_mean1"), abs))

试图策划这个...

ggplot(STmean1, aes(x=Target_depth_mean1, y=TS_mean1)) +
  geom_bar(stat="identity") +
  scale_y_continuous(
    limits = c(50, 30), 
                     oob= rescale_none,
                     labels=function(x) paste0("-",x)) #upside down

我究竟做错了什么? 我觉得我是如此接近,但无法让它发挥作用。 我已经尝试了几个小时并查看了其他 SO 问题,但没有运气......尝试了这个问题的答案,但没有奏效。

基于此答案,您可以执行以下操作:

ggplot(STmean, aes(x=Target_depth_mean1, y=TS_mean1 - min(TS_mean1))) +
  geom_bar(stat="identity", position = "dodge") +
  scale_y_continuous(breaks = seq(from = min(STmean$TS_mean1),
                                  to = max(STmean$TS_mean1), by = 1) - min(STmean$TS_mean1),
                     labels = seq(from = min(STmean$TS_mean1),
                                  to = max(STmean$TS_mean1), by = 1)) + 
  ylab("TS_mean1")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM