[英]How can I add text labels showing the amount of data points in a geom_jitter plot?
I have a geom_jitter plot with a categorical variable in x axis and a continuous variable in y axis.我有一个 geom_jitter 图,在 x 轴上有一个分类变量,在 y 轴上有一个连续变量。 I want to plot on top of the maximum value of each x axis category the total number of data points contained in that category, which would be basically plotting the output of
我想在每个 x 轴类别的最大值之上绘制该类别中包含的数据点总数,这基本上是绘制输出
table(my_df$my_categorical_var)
So far I've tried:到目前为止,我已经尝试过:
+geom_text(aes(x= my_categorical_var), y= max(my_continuous_var), label=as.vector(my_df$my_categorical_var))
But this outputs an error:但这会输出一个错误:
Error in `geom_text()`:
! Problem while computing aesthetics.
ℹ Error occurred in the 2nd layer.
Caused by error in `check_aesthetics()`:
! Aesthetics must be either length 1 or the same as the data
(20996)
✖ Fix the following mappings: `label`
Which basically makes you create a geom_text for each label or to modify the dataframe and add a new column for each category containing the number that I want to plot.这基本上让您为每个标签创建一个 geom_text 或修改数据框并为每个类别添加一个新列,其中包含我要绘制的数字。 However there might be something more straigforward.
然而,可能还有更直接的东西。
My desired output would be something like the following plot with a top label with the count of data points of each category:我想要的输出类似于下图,顶部标签带有每个类别的数据点数:
You could pass a summarized version of the data to your geom_text
layer:您可以将数据的汇总版本传递给
geom_text
层:
library(ggplot2)
library(dplyr)
ggplot(mpg, aes(cyl, hwy)) +
geom_point(position = position_jitter(width = 1/3)) +
geom_text(data = . %>%
group_by(cyl) %>%
summarize(hwy = max(hwy), label = n()),
aes(label = label), nudge_y = 5, color = 'red')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.