简体   繁体   English

在R / ggplot2中突出显示密度和小提琴图上的个别观察

[英]Highlight individual observation in density and violin plot in R/ggplot2

I am trying to highlight the position of an individual in a density plot and in a violin plot. 我试图强调一个人在密度图和小提琴图中的位置。

For instance, in the plot generated by the code bellow, I would like highlight "Mazda RX4" in the mtcars dataset. 例如,在由代码波纹管生成的图中,我想在mtcars数据集中突出显示“ Mazda RX4”。 This could be by adding a point or bar to the value of that individual observation in each category 这可以通过在每个类别中的单个观察值上添加一个点或条来实现

#density plot
ggplot(data=mtcars,aes(x=drat))+
  geom_density() + facet_grid(cyl ~ .)

#violin plot
library(ggplot2)
ggplot(data=mtcars,aes(x=factor(cyl),y=drat, fill=factor(am)))+
  geom_violin() 

EDIT: 1) Based on @DatamineR answer bellow I as able to add the desired point (code bellow) to the violin plot. 编辑:1)基于@DatamineR的答案,我能够将所需的点(波纹管)添加到小提琴图。

ggplot(data=mtcars,aes(x=factor(cyl),y=drat, fill=factor(am)))+ 
  geom_violin() + geom_point(data = mtcars[rownames(mtcars) == "Mazda RX4",])

However, the same +geom_point() did not work with the density plot. 但是,相同的+ geom_point()不适用于密度图。 How can I add a point for that observation for the density plot? 如何为密度图的观测值添加一个点?

2) Also, is it possible to use another marker, like a line segment or bar (perpendicular to the base line of the distribution) instead of a point? 2)另外,是否可以使用其他标记(例如线段或条形图(垂直于分布的基线))代替点?

Try the following for the first part of the question (add to your ggplot-code): 对于问题的第一部分,尝试以下操作(添加到ggplot代码中):

geom_point(data = mtcars[rownames(mtcars) == "Mazda RX4",])

在此处输入图片说明

For the second part of the question you can try(add to your ggplot-code): 对于问题的第二部分,您可以尝试(添加到ggplot代码中):

geom_point(data = mtcars[rownames(mtcars) == "Mazda RX4",], aes(y = 0))

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM