如何在条形图上更正 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")
The Data
您所指的问题包含一个很好的想法,可以改用 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 package (v2.0.1)
于 2021-10-19 创建
使用钻孔数据,尝试用 R 绘制横截面。我生疏了,无法按照我想要的方式组织绘图。从图像中,我的条形图没有跟踪显示钻孔深度的 y 轴值,而是跟踪图层(分类数据)。
有人问了非常相似的问题
澄清一下,我想将 y 轴按数字递增顺序排列,从 0 开始,并将分类层数据映射到该深度的正确部分。
我的代码:
g2 <- ggplot(data=df3,
mapping = aes(x=PointID,y=End_Depth,
fill=`Layer`)) +
geom_col(colour="black") +
labs(y="Depth")
The Data
您所指的问题包含一个很好的想法,可以改用 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 package (v2.0.1)
于 2021-10-19 创建