簡體   English   中英

如何在條形圖上更正 R 中 y 軸的比例和順序

[英]How do I correct the scale and order of the y axis in R on a barplot

使用鑽孔數據,嘗試用 R 繪制橫截面。我生疏了,無法按照我想要的方式組織繪圖。 從圖像中可以看出,我的條形圖沒有使用顯示鑽孔深度的 y 軸值進行跟蹤,而是使用圖層(分類數據)進行跟蹤。

這里提出非常相似的問題,但我無法讓代碼適用於我的情況,因為我的數據格式不同。

只是為了澄清,我想將 y 軸按數字遞增順序排列,從 0 開始,將分類層數據映射到該深度的正確部分。

我的代碼:

g2 <- ggplot(data=df3,
        mapping = aes(x=PointID,y=End_Depth,
                      fill=`Layer`)) +
  geom_col(colour="black") +
  labs(y="Depth")

圖表現在如何

數據

您所指的問題包含一個很好的主意,即改用 geom_rect。 您可以執行以下操作(代碼中的注釋)

library(tidyverse)

# just some fake data, similar to yours
foo <- data.frame(id = "id", layer = letters[1:6], depth = c(5,10,12,15,20,25))

foo2 <- 
  foo %>%
  # using lag to create ymin, which is needed for geom_rect
  # transforming id into integers so i can add / subtract some x for xmin/xmax
  mutate( ymin = lag(depth, default = 0),
         id_int = as.integer(factor(id))) 
  
# I am turning off the legend and labelling the layers directly instead 
# using geom_text
# this creates a "wrong" y axis title which I'm changing with labs(y = ... )
# the continuous x axis needs to be turned into a fake discrete axis by
# semi-manually setting the breaks and labels
ggplot(foo2) +
  geom_rect(aes(xmin = id_int - .5, xmax = id_int +.5, 
                ymin = ymin, ymax = depth,
                fill = layer), show.legend = FALSE) +
  geom_text(aes(x = id_int, y = (depth + ymin)/2, label = layer)) +
  scale_x_continuous(breaks = foo2$id_int, labels = foo2$id) +
  labs(y = "depth") 

reprex 包(v2.0.1) 於 2021 年 10 月 19 日創建

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM