简体   繁体   中英

How to create consistent x axis values in ggplot

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

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 eg 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM