I want to create a graph in ggplot. I want the x axis to have commonly used values that make it easy to read. For example, -50%, -25%, 0%, 25%, 50%
I have a data frame data
that looks like:
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)
This creates the graph, however, the x values are all the exact values from the graph:
I have tried coord_cartesian(xlim =c(-100, 100))
However, it makes the graph looks less than ideal:
graph
I have tried scale_x_continuous(labels = c(-100,-50,0,50,100,150,200))
but I receive:
Error: Discrete value supplied to continuous scale
CodePudding user response:
The issue is that your PercentageColumn
is a character (a discrete variabe) so that each value is treated as a unique category.
Hence, convert first to a numeric using e.g. readr::parse_number
. As a second step you could label as percentages and set your desired breaks and limits via 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)