簡體   English   中英

如何合並顏色和形狀?

[英]How to merge colour and shape?

當我有一個超過6個值的變量時,我的麻煩就開始了,因為這是ggplot2中scale_shape函數的當前最大值。

由於這個問題,我嘗試了另一個變量,我只是圍繞原始變量的長度。

這是我的示例代碼:

dataf <- structure(list(Municipality = structure(c(2L, 4L, 10L, 11L, 6L, 8L, 3L, 1L, 5L, 9L, 7L), .Label = c("Boyuibe", "Cabezas", "Camiri", "Charagua", "Cuevo", "Gutierrez", "Huacaya", "Lagunillas", "Machareti", "Vallegrande", "Villa Vaca Guzman"), class = "factor"), Growth = c(3.05, 2.85, 0.14, 1.21, 1.59, 2.35, -0.41, 0.81, 0.9, 2.89, 1.8), Density = c(3.0390920594, 0.260984024187, 5.20069847261, 2.50828556783, 3.43964629267, 3.69768961375, 32.4496626479, 2.06145019368, 4.2139578988, 0.740736713557, 1.67034079825)), .Names = c("Municipality", "Growth", "Density"), class = "data.frame", row.names = c(NA, -11L))

dataf <- dataf[with(dataf, order(Municipality)), ]
# create a new column with values 1 to 6 and same length as Municipality
modulus <- function(x) (x - 1) %% 6 + 1
indeces <- 1:length(dataf$Municipality)
dim(indeces) <- length(dataf$Municipality)
dataf$Shape <- apply(indeces, 1, modulus)
dataf$Shape <- factor(dataf$Shape, levels=unique(dataf$Shape))
plot1 <- ggplot(dataf, aes(x=Density, y=Growth, colour=Municipality,
        shape=Shape))
plot1 <- plot1 + geom_point(size=3)
plot1 <- plot1 + scale_x_continuous(expression(paste(
        "Population Density [people per km"^2, "]", sep="")))
plot1 <- plot1 + scale_y_continuous("Growth Rate [ratio population 2001 /
        population 1992]")
plot1 <- plot1 + scale_colour("Municipality")
plot1

產生以下輸出: 在此輸入圖像描述

我希望傳說就像情節中的點。 這是可能的,還是有一個聰明的解決方案,我的第一個問題與市政當局的名單太長了?

提前致謝。

這是一個例子:

plot1 <- ggplot(dataf, aes(x=Density, y=Growth, colour=Municipality,
        shape=Municipality))
plot1 <- plot1 + geom_point(size=3)
plot1 <- plot1 + scale_colour_discrete() + 
scale_shape_manual(values=as.numeric(dataf$Shape))
plot1

如果你需要填充形狀,然后替換為

scale_shape_manual(values=c(16, 17, 15, 3, 7, 8)[as.numeric(dataf$Shape)])

技巧是:

  1. 使用相同的變量顏色和形狀(市政)
  2. 使用scale_shape_manual並制作斷點(此處為市政)和值(此處為dataf $ Shape)的映射
  3. 你需要數字變量而不是scale_shape_manual值的因子

進一步的技巧:如果你給任何一個圖例命名,你必須給它們兩個相同的名字。 如果只給一個圖例命名,ggplot將再次分隔圖例。 修改kohske的例子:

plot1 <- ggplot(dataf, aes(x=Density, y=Growth, colour=Municipality,
        shape=Municipality)) + geom_point(size=3)

plot2 <- plot1 + scale_colour_discrete() + 
scale_shape_manual(values=as.numeric(dataf$Municipality))

plot2

plot3 <- plot1 + scale_colour_discrete('City') + 
scale_shape_manual(values=as.numeric(dataf$Municipality))

plot3

plot4 <- plot1 + scale_colour_discrete('City') + 
scale_shape_manual('City',values=as.numeric(dataf$Municipality))

plot4

使用scale_shape_manual()怎么樣? 如果我理解你的問題,你真的不需要區分顏色和形狀,而是喜歡形狀,對嗎?

ggplot(dataf, aes(x=Density, y=Growth)) + 
  geom_point(aes(shape = Municipality)) +
  scale_shape_manual(values = 1:11)

生產: 在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM