簡體   English   中英

使用ggplot手動選擇顏色和軸名稱進行R氣泡圖

[英]R bubble plot using ggplot manually selecting the colour and axis names

我使用ggplot創建氣泡圖。 使用此代碼:

ggplot(df, aes(x = order, y = mean, size = n, fill = name)) +
  geom_point(shape = 21) +
  theme_bw() +
  theme() + 
  scale_size(range = c(1, 50)) + 
  ylim(0,100)

除了以下兩點之外,它的工作原理非常完美:

  1. 對於每個名稱(填充),我想手動指定使用的顏色(通過將名稱映射到顏色的數據框)-這是為了在多個圖形之間提供一致性。
  2. 我想用y上的數字代替文本標簽(由於多種原因,由於訂購問題,我無法從一開始就使用文本標簽)

我已經嘗試分別使用scale_color_manual()和scale_y_continuous的幾種方法,但我無濟於事! 任何幫助將不勝感激!

謝謝

由於您尚未指定示例df ,因此我創建了一個示例。

要手動指定顏色,您必須使用帶有命名向量的scale_fill_manual作為values的參數。

編輯2

這似乎在做您想要的。 我們使用scale_y_continuous breaks參數指定位置的向量,而labels參數指定應該出現在這些位置的標簽。 由於在創建數據幀時已經創建了向量,因此我們只需將這些向量作為參數傳遞即可。

ggplot(df, aes(x = order, y = mean, size = n, fill = name)) +
  geom_point(shape = 21) +
  scale_fill_manual(values = gcolors) +
  scale_size(limits = c(min(df$n), max(df$n))) +
  scale_y_continuous(breaks = mean, labels = order_label)

編輯1

從您的評論看來,您想標記圓圈。 一種選擇是使用geom_text 下面的代碼。 您可能需要嘗試使用nudge_y值來獲得正確的位置。

order <- c(1, 2)
mean <- c(0.75, 0.3)
n <- c(180, 200)
name <- c("a", "b")
order_label <- c("New York", "London")
df <- data.frame(order, mean, n, name, order_label, stringsAsFactors = FALSE)

color <- c("blue", "red")
name_color <- data.frame(name, color, stringsAsFactors = FALSE)
gcolors <- name_color[, 2]
names(gcolors) <- name_color[, 1]

ggplot(df, aes(x = order, y = mean, size = n, fill = name)) +
  geom_point(shape = 21) +
  geom_text(aes(label = order_label), size = 3, hjust = "inward",
            nudge_y = 0.03) +
  scale_fill_manual(values = gcolors) +
  scale_size(limits = c(min(df$n), max(df$n))) +
  theme(axis.text.y = element_blank(),
        axis.ticks.y = element_blank()) +
  ylab(NULL)

原始答案

您不清楚“用y上的數字替換文本標簽”是什么意思。 在下面的示例中,我已使用scales::percent_format()函數將y軸格式化為百分比。 這類似於您想要的嗎?

order <- c(1, 2)
mean <- c(0.75, 0.3)
n <- c(180, 200)
name <- c("a", "b")
df <- data.frame(order, mean, n, name, stringsAsFactors = FALSE)

color <- c("blue", "red")
name_color <- data.frame(name, color, stringsAsFactors = FALSE)
gcolors <- name_color[, 2]
names(gcolors) <- name_color[, 1]

ggplot(df, aes(x = order, y = mean, size = n, fill = name)) +
  geom_point(shape = 21) +
  scale_fill_manual(values = gcolors) +
  scale_size(limits = c(min(df$n), max(df$n))) +
  scale_y_continuous(labels = scales::percent_format())

謝謝,在您的所有幫助下,此方法非常有效:

ggplot(df, aes(x = order, y = mean, size = n, fill = name)) +
  geom_point(shape = 21) +
  scale_fill_manual(values = gcolors) +
  scale_size(limits = c(min(df$n), max(df$n))) +
  scale_x_continuous(breaks = order, labels = order_label)

暫無
暫無

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

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