如何使用带有负y值的geom_bar制作竖条?

zxlwwiss  于 2022-12-20  发布在  其他
关注(0)|答案(1)|浏览(166)

我正尝试使用ggplot制作下面的条形图(如果基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问题,但没有运气...尝试了this问题中的答案,但没有工作。

k4emjkb1

k4emjkb11#

基于this answer,您可以执行以下操作:

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")

相关问题