我是 R 的新手,現在我正在處理一個長資料集一段時間,最終得到 2 列(國家和利潤):
y <- data.frame(tapply(sub$Profit, sub$Country, sum))
y <- rename(y, Profit = tapply.sub.Profit..sub.Country..sum.)
y <- cbind(Country = rownames(y), y)
rownames(y) <- 1:nrow(y)
y <- y %>% arrange( Profit)
y
0 Country Profit
1 Slovakia 56264.49
2 Luxembourg 59903.52
3 Ireland 104150.35
4 Sweden 109208.67
5 Finland 137918.93
6 Norway 159719.46
7 Portugal 199447.42
8 Netherlands 214398.10
9 Switzerland 248677.00
10 Czech Republic 286430.06
11 Denmark 305669.83
12 Belgium 316599.95
13 Poland 349640.12
14 Austria 397716.80
15 Italy 433439.35
16 Spain 520474.14
17 France 525408.81
18 United Kingdom 565622.63
19 Germany 643194.62
現在我試圖用它繪制一個條形圖,但我很掙扎。
graph_country_profit <- ggplot(y, aes(x=Profit,y=Country)) geom_col(width = 0.5, aes(fill="Profit"))
graph_country_profit
但圖表排在第一位。粉紅色,第 2 名。用奇怪的數字。我該如何解決?任何解釋為什么會這樣?也可以訂購它增加/減少嗎?
感謝您的時間和幫助!
uj5u.com熱心網友回復:
為什么你的情節是粉紅色的答案是因為你在你的aes函式中參考了利潤。這是我重新創建您的資料集:
data <- tibble(
Country = c(
"Slovakia", "Luxembourg", "Ireland", "Sweden", "Finland", "Norway", "Portugal",
"Netherlands", "Switzerland", "Czech Republic", "Denmark", "Belgium", "Poland",
"Austria", "Italy", "Spain", "France", "United Kingdom", "Germany"
),
Profit = c(56264.49, 59903.52, 104150.35, 109208.67, 137918.93, 159719.46, 199447.42,
214398.10, 248677.00, 286430.06, 305669.83, 316599.95, 349640.12, 397716.80,
433439.35, 520474.14, 525408.81, 565622.63, 643194.62)
)
這是我運行您的代碼:
ggplot(
data,
aes(
x=Profit,
y=Country)
)
geom_col(
width = 0.5,
aes(
fill = "Profit"
)
)

讓我們再次運行它,但這次取消參考aes函式中的填充引數
ggplot(
data,
aes(
x=Profit,
y=Country)
)
geom_col(
width = 0.5,
aes(
fill = Profit
)
)

現在,每個條都由利潤著色。
發生這種情況的原因是美學功能正在尋找一個變數來為您的繪圖著色。按照慣例,您不要用引號將它們括起來。如果您確實用引號將其括起來,它將不會將其識別為變數,而只會將其視為隨機字串。隨機字串不包含有關應該以何種方式著色哪個條的資訊,因此 ggplot 只是將每個條著色為相同的顏色。
通過“奇怪的數字”,我假設您的意思是“2e 05”,如果您以前沒有見過,這只是表示 2x10^5 或 200000。TarJae 的另一個答案顯示了如何使用scale_y_continuous以及如何重新排序因素來解決此問題。
uj5u.com熱心網友回復:
library(tidyverse)
library(scales)
ggplot(df, aes(y=Profit,x=fct_reorder(Country, Profit), fill=Profit))
geom_col(width = 0.5)
coord_flip()
scale_fill_gradient(low = "blue", high = "red", name = "Trade Value", labels = comma)
scale_y_continuous(labels = function(x) format(x, scientific = FALSE))
theme_classic()

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/420805.html
標籤:
上一篇:假陽性與假陰性權衡圖
下一篇:ggplot中兩個變數的軸標簽?
