我想在 ggplot 中創建一個圖表。我希望 x 軸具有易于閱讀的常用值。例如,-50%, -25%, 0%, 25%, 50%
我有一個如下所示的資料框data:
Specialty,PercentageChange,mycolor
T,-20.23%,brown
T,-20.29%,brown
graph<-ggplot(data, aes(x=PercentageChange, y=Specialty,color=mycolor,size=5))
geom_point()
theme_gray(base_size = 14)
這將創建圖形,但是,x 值都是圖形中的精確值:

我試過了 coord_cartesian(xlim =c(-100, 100))
但是,它使圖形看起來不太理想:
圖形
我試過了,scale_x_continuous(labels = c(-100,-50,0,50,100,150,200))
但我收到:
Error: Discrete value supplied to continuous scale
uj5u.com熱心網友回復:
問題在于您PercentageColumn是一個字符(一個離散變數),因此每個值都被視為一個唯一的類別。
因此,首先使用例如轉換為數字readr::parse_number。第二步,您可以標記為百分比并通過scale_x_continuous以下方式設定所需的中斷和限制:
library(ggplot2)
data <- structure(list(Specialty = c(TRUE, TRUE), PercentageChange = c(
"-20.23%",
"-20.29%"
), mycolor = c("brown", "brown")), class = "data.frame", row.names = c(
NA,
-2L
))
data$PercentageChange <- readr::parse_number(data$PercentageChange) / 100
ggplot(data, aes(x = PercentageChange, y = Specialty, color = mycolor, size = 5))
geom_point()
scale_x_continuous(labels = scales::percent_format(), breaks = seq(-1, 1, .25), limits = c(-1, 1))
theme_gray(base_size = 14)

轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/368356.html
