我試圖只標記 ggplot2 中的一部分條形圖。我認為以下內容會起作用,但它默認為標記組的中心。
library(tidyverse)
#> -- Attaching packages --------------------------------------- tidyverse 1.3.1 --
#> v ggplot2 3.3.5 v purrr 0.3.4
#> v tibble 3.1.6 v dplyr 1.0.7
#> v tidyr 1.1.4 v stringr 1.4.0
#> v readr 2.1.1 v forcats 0.5.1
#> -- Conflicts ------------------------------------------ tidyverse_conflicts() --
#> x dplyr::filter() masks stats::filter()
#> x dplyr::lag() masks stats::lag()
df <- iris |>
pivot_longer(-Species) |>
count(Species, name, wt = value, name = "value")
df |>
ggplot(aes(x = name, y = value, fill = Species))
geom_col(position = position_dodge())
geom_text(data = df[df$Species == "setosa", ], aes(label = value))

所以在這里我想給標簽setosa貼上標簽。
uj5u.com熱心網友回復:
首先,您必須添加position_dodge(width = .9以與條形相同的量來躲避文本標簽,其中 .9 是 .9 的默認寬度geom_col。
但是,為了使躲避作業所有組都必須出現在您的資料中,因此您也必須使用整個資料框geom_text。要僅標記一個組,請使用例如 anifelse將其他類別的標簽設定為空字串。
library(ggplot2)
library(dplyr)
library(tidyr)
df <- iris |>
pivot_longer(-Species) |>
count(Species, name, wt = value, name = "value")
df |>
ggplot(aes(x = name, y = value, fill = Species))
geom_col(position = position_dodge())
geom_text(aes(label = ifelse(Species == "setosa", value, "")),
position = position_dodge(width = .9), vjust = 0)

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/416767.html
標籤:
上一篇:如何移動x軸上每個分類變數的半小提琴圖(外部)、箱線圖(中間)和geom_points(內部)?ggplot2,R
下一篇:將條形從低到高重新排序
