![](/img/trans.png)
[英]How to change x-axis tick label names, order and boxplot colour using R ggplot?
[英]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)
除了以下兩點之外,它的工作原理非常完美:
我已經嘗試分別使用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.