【问题标题】:Change point colors and color of frame/ellipse around points更改点颜色和点周围框架/椭圆的颜色
【发布时间】:2016-02-11 22:48:37
【问题描述】:

首先我想说我是 R 的新手,尤其是这个网站的新手,所以如果有必要在这里澄清任何事情,请告诉我!我还不太了解所有内容,因此请随时“低调”。

问题:我想创建描述两组(在本例中为物种)的 PCA 图。我还想在它们周围绘制椭圆或框架。

谢天谢地,我使用 ggplot2 完成了这项任务! 但是,我无法更改超出默认值的点或椭圆/框架的颜色。

您能否就此事提供一些帮助?

请看下面的示例代码,这只是PCA示例中经常使用的传统鸢尾花数据集。

###load in plackages###
library(ggbiplot)
library(ggfortify)
library(cluster)

#my actual data is very similar to the iris data, though in my data the     "Species" column is first
head(iris)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa
df <- iris[c(1, 2, 3, 4)]
autoplot(prcomp(df))
autoplot(prcomp(df), data = iris, colour = 'Species') #pca graph with   species depicted in different colors

autoplot(prcomp(df), data = iris, colour = 'Species', shape='Species', frame=T) 

【问题讨论】:

  • 我现在无法安装 ggbiplot,但您是否尝试过传递 scale_color_manual(此处的 3 个自定义值)?
  • scale_fill_manual 用于框架。 ggplot2 周围有很多示例,只需搜索,例如,“ggplot2 手动设置颜色”。您可以编辑您的问题,以明确您包含的代码依赖于 ggfortify 而不是其他任何一个包(据我所知)。
  • 谢谢@aosmith!你给的这个建议很完美!我发布了我在下面找到的解决方案。

标签: r ggplot2 pca ggfortify


【解决方案1】:

我也做了同样的 PCA

data<-iris
df<-iris[c(1, 2, 3, 4)]
PC<-prcomp(df)
PCi<-data.frame(PC$x,Species=data$Species)

现在您可以正常绘图并像往常一样更改ggplot 参数

ggplot(PCi,aes(x=PC1,y=PC2,col=Species))+
   geom_point(size=3,alpha=0.5)+ #Size and alpha just for fun
   scale_color_manual(values = c("#FF1BB3","#A7FF5B","#99554D"))+ #your colors here
   theme_classic()

另外,检查 scale_fill_manual 的框架

编辑

我认为添加框架应该更容易,请查看https://stats.stackexchange.com/questions/22805/how-to-draw-neat-polygons-around-scatterplot-regions-in-ggplot2
和这里 ggplot2: geom_polygon with no fill

另外,我仍然认为 ggbiplot 应该处理 scale_color_manualscale_fill_manual,您能否更新您失败的问题?

【讨论】:

  • 我认为添加框架应该更容易,检查这里stats.stackexchange.com/questions/22805/…
  • 谢谢@Matias!对于我的解决方案,我有您使用过的建议 scale_ color_manualscale_fill_manual。这正是我所需要的!
【解决方案2】:

酱汁真棒!

答案在这些示例中并没有完全隐藏,但我发现 scale_color_manual 和 scale_fill_manual 完全符合我的要求:将框架更改为任何可以想象的颜色!

#using autoplot from earlier, I placed it into an object
a<-autoplot(prcomp(df), data = iris, colour = 'Species', shape='Species', frame=T)
#then I added on scale_color_manual and scale_fill_manual with the wacky color combos that would never be publishable 
a + scale_fill_manual(values = c("#FF1BB3","#A7FF5B","#99554D")) + scale_color_manual(values = c("black","white","orange")) 

PCA GRAPH WITH DIFFERENT COLORS

非常感谢您的帮助!非常感谢这里有这个小(或者相当大)的小组!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多