在散点图中正确使用颜色

时间:2017-12-08 19:05:12

标签: r ggplot2 scatterpie

我想使用scatterpie制作6个不同的馅饼。有101种不同的类别构成馅饼(并非所有的馅饼都有101种),所以我希望能够区分颜色。

这不会给我足够的颜色(我只能通过看馅饼来判断)

ggplot(wholebody_cutLH_wide_t) +
#  annotation_custom(g, xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf) +
geom_scatterpie(aes(x=imX, y=imY,r=radius),
            data=wholebody_cutLH_wide_t,     cols=colnames(wholebody_cutLH_wide_t[1:101]),color=NA) +
#scale_color_manual(values=sample(allcolors,101)) +
 scale_x_continuous(expand=c(0,0), lim=c(0,3)) +
scale_y_continuous(expand=c(0,0), lim=c(0,6)) +
theme(legend.position="none",
    panel.background = element_rect(fill = "transparent") # bg of the panel
    , plot.background = element_rect(fill = "transparent") # bg of the plot
    , panel.grid.major = element_blank() # get rid of major grid
    , panel.grid.minor = element_blank(), # get rid of minor grid
    line = element_blank(),
    text = element_blank(),
    title = element_blank()
)  

enter image description here

然后,如果我尝试手动设置颜色如下,我得到一个空白屏幕。 如果我尝试在scatterpie中设置颜色(color = sample(allcolors,101)),那么我得到错误

错误:美学必须是长度1或与数据(2864)相同:颜色

allcolors = grDevices::colors()[grep('gr(a|e)y', grDevices::colors(), invert = T)]
ggplot(wholebody_cutLH_wide_t) +
#  annotation_custom(g, xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf) +
geom_scatterpie(aes(x=imX, y=imY,r=radius),
            data=wholebody_cutLH_wide_t, cols=colnames(wholebody_cutLH_wide_t[1:101]),color=NA) +
scale_color_manual(values=sample(allcolors,101)) +
scale_x_continuous(expand=c(0,0), lim=c(0,3)) +
scale_y_continuous(expand=c(0,0), lim=c(0,6)) +
theme(legend.position="none",
    panel.background = element_rect(fill = "transparent") # bg of the panel
    , plot.background = element_rect(fill = "transparent") # bg of the plot
    , panel.grid.major = element_blank() # get rid of major grid
    , panel.grid.minor = element_blank(), # get rid of minor grid
    line = element_blank(),
    text = element_blank(),
    title = element_blank()
 )  

1 个答案:

答案 0 :(得分:2)

这是最终的工作代码。我不得不将scale_color_manual切换为scale_fill_manual。

ggplot(wholebody_cutLH_wide_t) +
annotation_custom(g, xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf) +
geom_scatterpie(aes(x=imX, y=imY,r=radius),
            data=wholebody_cutLH_wide_t, cols=colnames(wholebody_cutLH_wide_t)[1:101],color=NA) +
scale_fill_manual(values=sample(allcolors,101)) +
scale_x_continuous(expand=c(0,0), lim=c(0,3)) +
scale_y_continuous(expand=c(0,0), lim=c(0,6)) +
theme(legend.position="none",
    panel.background = element_rect(fill = "transparent") # bg of the panel
    , plot.background = element_rect(fill = "transparent") # bg of the plot
    , panel.grid.major = element_blank() # get rid of major grid
    , panel.grid.minor = element_blank(), # get rid of minor grid
    line = element_blank(),
    text = element_blank(),
    title = element_blank()
)  

这是情节

enter image description here