Discrete value supplied to continuous scale即使我使用的是數字變數,我也會收到重復的錯誤訊息“ ”。
這是我的代碼
name = c("Alberto Manguel", "Alberto Manguel","Alberto Manguel","Alberto Manguel","Alberto Manguel","Alberto Manguel","Alberto Manguel","Alberto Manguel","Alberto Manguel","Alberto Manguel",)
year = c(1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999)
portion = c(0.0044117647, 0.0191846523, 0.0151898734, 0.0042075736, 0.0044493882, 0.0021881838, 0.0146396396, 0.0162689805, 0.0136054422, 0.0158730159)
df <- tibble(name, year, portion)
ggplot(df) geom_line(aes(x = year, y = portion, group = name), colour="black") geom_text(aes(year == 1999, label = name), hjust = -.1)
我的year變數已經是數值了,不用再轉換了?我缺少什么?
uj5u.com熱心網友回復:
問題是 geom_text 行。大概您想在相應的點顯示每個名稱,因此將 x 和 y 的 aes 值放在 ggplot 中,以便與 geom_line 和 geom_text 共享它們,然后我們可以指定特定于每個名稱的美學。
library(ggplot2)
ggplot(df, aes(x = year, y = portion))
geom_line(aes(group = name), colour = "black")
geom_text(aes(label = name), hjust = -0.1)
或者如果目的是只標記最后一點,那么:
library(dplyr)
library(ggplot2)
ggplot(df, aes(x = year, y = portion))
geom_line(aes(group = name), colour = "black")
geom_text(aes(label = name), data = slice_tail, hjust = -0.1)
根據您想要的內容,可以將 slice_tail 替換為其中之一——波浪號是 data= 引數的一部分,表示它正在定義一個函式,ggplot2 將應用于定義中的點表示的 df。
~ slice_max(., year) # all rows having the largest year
~ filter(., year == 1999) # all rows having year 1999
~ group_by(., name) %>% slice_max(year) %>% ungroup # row of max year in each name
筆記
問題中顯示的輸入有錯誤,所以我們使用了這個:
name = c("Alberto Manguel", "Alberto Manguel","Alberto Manguel","Alberto Manguel","Alberto Manguel","Alberto Manguel","Alberto Manguel","Alberto Manguel","Alberto Manguel","Alberto Manguel")
year = c(1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999)
portion = c(0.0044117647, 0.0191846523, 0.0151898734, 0.0042075736, 0.0044493882, 0.0021881838, 0.0146396396, 0.0162689805, 0.0136054422, 0.0158730159)
df <- data.frame(name, year, portion)
uj5u.com熱心網友回復:
在這種情況下,X 和 Y 都應該是數字嗎?也是 Y 數字。如果你說你解決了問題應該依賴于 ggplot() 函式或某個層。
通過運行您的代碼,我發現該問題應該在 geom_text() 層中。沒有它,我們的情節很好。如果您想獲得特定點的名稱,這對我有用(盡管我不確定這是否是您的意圖!:
name <- c("Alberto Manguel", "Alberto Manguel","Alberto Manguel","Alberto Manguel","Alberto Manguel","Alberto Manguel","Alberto Manguel","Alberto Manguel","Alberto Manguel","Alberto Manguel")
year = c(1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999)
portion = c(0.0044117647, 0.0191846523, 0.0151898734, 0.0042075736, 0.0044493882, 0.0021881838, 0.0146396396, 0.0162689805, 0.0136054422, 0.0158730159)
df <- data.frame(name, year, portion)
plot <- ggplot() geom_line(aes(x = year, y = portion, group = name), colour="black")
geom_text(aes(x=year, y=portion, label=name))
它可能會因為將 NAME 作為離散變數而導致錯誤,因此它不能真正用作變數本身,而只能用作標簽?
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/369329.html
上一篇:如何在R中拆分“CHR”列?
