ggplot2 axis scales and transformations

  • Prepare the data
  • Case of plots
  • Change x and y axis limits
    • Use xlim() and ylim() functions
    • Employ expand_limts() function
    • Use scale_xx() functions
  • Axis transformations
    • Log and sqrt transformations
    • Format axis tick mark labels
    • Display log tick marks
  • Format engagement axes
    • Example of information
    • Create some time serie data
    • Plot with dates
    • Format centrality tick marker labels
    • Date axis limits
  • Go farther
  • Infos

This R tutorial describes how to alter x and y axis limits (minimum and maximum values) using ggplot2 package. Axis transformations (log calibration, sqrt, …) and engagement axis are as well covered in this article.


Gear up the information

ToothGrowth information is used in the following examples :

                  # Convert dose cavalcade dose from a numeric to a factor variable ToothGrowth$dose <- as.factor(ToothGrowth$dose) head(ToothGrowth)                
                  ##    len supp dose ## 1  4.2   VC  0.5 ## 2 11.five   VC  0.v ## 3  7.three   VC  0.five ## iv  five.8   VC  0.five ## 5  6.4   VC  0.v ## vi 10.0   VC  0.5                

Brand sure that dose column is converted as a factor using the higher up R script.

Instance of plots

                  library(ggplot2) # Box plot  bp <- ggplot(ToothGrowth, aes(10=dose, y=len)) + geom_boxplot() bp # scatter plot sp<-ggplot(cars, aes(x = speed, y = dist)) + geom_point() sp                

Change 10 and y axis limits

At that place are dissimilar functions to set axis limits :

  • xlim() and ylim()
  • expand_limits()
  • scale_x_continuous() and scale_y_continuous()

Utilise xlim() and ylim() functions

To change the range of a continuous axis, the functions xlim() and ylim() can be used as follow :

                    # ten centrality limits sp + xlim(min, max) # y axis limits sp + ylim(min, max)                  

min and max are the minimum and the maximum values of each centrality.

                    # Box plot : change y axis range bp + ylim(0,50) # scatter plots : modify x and y limits sp + xlim(5, 40)+ylim(0, 150)                  

Apply expand_limts() role

Note that, the function expand_limits() tin be used to :

  • quickly set the intercept of x and y axes at (0,0)
  • change the limits of 10 and y axes
                    # set up the intercept of 10 and y axis at (0,0) sp + expand_limits(ten=0, y=0) # change the axis limits sp + expand_limits(x=c(0,xxx), y=c(0, 150))                  

Use scale_xx() functions

It is also possible to use the functions scale_x_continuous() and scale_y_continuous() to change ten and y axis limits, respectively.

The simplified formats of the functions are :

                    scale_x_continuous(name, breaks, labels, limits, trans) scale_y_continuous(name, breaks, labels, limits, trans)                  

  • name : 10 or y axis labels
  • breaks : to control the breaks in the guide (axis ticks, grid lines, …). Among the possible values, at that place are :
    • Aught : hide all breaks
    • waiver() : the default break computation
    • a character or numeric vector specifying the breaks to brandish
  • labels : labels of axis tick marks. Allowed values are :
    • Naught for no labels
    • waiver() for the default labels
    • character vector to be used for suspension labels
  • limits : a numeric vector specifying x or y axis limits (min, max)
  • trans for axis transformations. Possible values are "log2", "log10", …

The functions scale_x_continuous() and scale_y_continuous() can be used as follow :

                    # Alter x and y axis labels, and limits sp + scale_x_continuous(proper noun="Speed of cars", limits=c(0, xxx)) +   scale_y_continuous(proper name="Stopping distance", limits=c(0, 150))                  

Axis transformations

Log and sqrt transformations

Built in functions for axis transformations are :

  • scale_x_log10(), scale_y_log10() : for log10 transformation
  • scale_x_sqrt(), scale_y_sqrt() : for sqrt transformation
  • scale_x_reverse(), scale_y_reverse() : to contrary coordinates
  • coord_trans(x ="log10", y="log10") : possible values for x and y are "log2", "log10", "sqrt", …
  • scale_x_continuous(trans='log2'), scale_y_continuous(trans='log2') : another allowed value for the statement trans is 'log10'

These functions can be used equally follow :

                    # Default scatter plot sp <- ggplot(cars, aes(10 = speed, y = dist)) + geom_point() sp # Log transformation using scale_xx() # possible values for trans : 'log2', 'log10','sqrt' sp + scale_x_continuous(trans='log2') +   scale_y_continuous(trans='log2') # Sqrt transformation sp + scale_y_sqrt() # Reverse coordinates sp + scale_y_reverse()                                      

The function coord_trans() tin exist used too for the axis transformation

                    # Possible values for x and y : "log2", "log10", "sqrt", ... sp + coord_trans(ten="log2", y="log2")                  

Format centrality tick mark labels

Axis tick marks can be ready to show exponents. The scales bundle is required to admission break formatting functions.

                    # Log2 scaling of the y centrality (with visually-equal spacing) library(scales) sp + scale_y_continuous(trans = log2_trans()) # show exponents sp + scale_y_continuous(trans = log2_trans(),     breaks = trans_breaks("log2", office(x) ii^10),     labels = trans_format("log2", math_format(ii^.10)))                  

Note that many transformation functions are available using the scales package : log10_trans(), sqrt_trans(), etc. Apply help(trans_new) for a full listing.

Format centrality tick mark labels :

                    library(scales) # Percent sp + scale_y_continuous(labels = percent) # dollar sp + scale_y_continuous(labels = dollar) # scientific sp + scale_y_continuous(labels = scientific)                  

Brandish log tick marks

It is possible to add log tick marks using the function annotation_logticks().

Note that, these tick marks make sense only for base 10

The Animals data sets, from the parcel MASS, are used :

                    library(MASS) head(Animals)                  
                    ##                     body encephalon ## Mount beaver     ane.35   viii.1 ## Cow               465.00 423.0 ## Grey wolf          36.33 119.5 ## Goat               27.66 115.0 ## Guinea pig          1.04   5.5 ## Dipliodocus     11700.00  l.0                  

The function annotation_logticks() tin exist used equally follow :

                    library(MASS) # to access Animals data sets library(scales) # to access break formatting functions # x and y axis are transformed and formatted p2 <- ggplot(Animals, aes(x = body, y = brain)) + geom_point() +      scale_x_log10(breaks = trans_breaks("log10", function(x) 10^x),               labels = trans_format("log10", math_format(ten^.x))) +      scale_y_log10(breaks = trans_breaks("log10", role(x) 10^x),               labels = trans_format("log10", math_format(ten^.x))) +      theme_bw() # log-log plot without log tick marks p2 # Bear witness log tick marks p2 + annotation_logticks()                                      

Note that, default log ticks are on bottom and left.

To specify the sides of the log ticks :

                    # Log ticks on left and correct p2 + annotation_logticks(sides="lr") # All sides p2+annotation_logticks(sides="trbl")                  

Allowed values for the statement sides are :

  • t : for top
  • r : for right
  • b : for bottom
  • l : for left
  • the combination of t, r, b and fifty

Format appointment axes

The functions scale_x_date() and scale_y_date() are used.

Case of data

Create some time serie data

                    df <- data.frame(   date = seq(Sys.Date(), len=100, past="1 mean solar day")[sample(100, fifty)],   price = runif(50) ) df <- df[order(df$date), ] head(df)                  
                    ##          date      price ## 33 2016-09-21 0.07245190 ## 3  2016-09-23 0.51772443 ## 23 2016-09-25 0.05758921 ## 43 2016-09-26 0.99389551 ## 45 2016-09-27 0.94858770 ## 29 2016-09-28 0.82420890                  

Plot with dates

                    # Plot with appointment dp <- ggplot(data=df, aes(x=date, y=price)) + geom_line() dp                  

Format centrality tick mark labels

Load the packet scales to admission interruption formatting functions.

                    library(scales) # Format : month/day dp + scale_x_date(labels = date_format("%chiliad/%d")) +   theme(centrality.text.x = element_text(bending=45)) # Format : Calendar week dp + scale_x_date(labels = date_format("%Due west")) # Months but dp + scale_x_date(breaks = date_breaks("months"),   labels = date_format("%b"))                  

Note that, since ggplot2 v2.0.0, date and datetime scales now have date_breaks, date_minor_breaks and date_labels arguments and then that you never need to use the long scales::date_breaks() or scales::date_format().

Appointment axis limits

US economic time series data sets (from ggplot2 package) are used :

                    head(economics)                  
                    ##         appointment   pce    pop psavert uempmed unemploy ## one 1967-07-01 507.4 198712    12.5     4.5     2944 ## two 1967-08-01 510.5 198911    12.5     iv.7     2945 ## 3 1967-09-01 516.3 199113    11.vii     4.6     2958 ## 4 1967-10-01 512.9 199311    12.5     4.ix     3143 ## 5 1967-eleven-01 518.1 199498    12.five     four.7     3066 ## vi 1967-12-01 525.8 199657    12.1     4.8     3018                  

Create the plot of psavert past date :

  • date : Calendar month of data drove
  • psavert : personal savings charge per unit
                    # Plot with dates dp <- ggplot(data=economics, aes(x=date, y=psavert)) + geom_line() dp # Centrality limits c(min, max) min <- as.Engagement("2002-1-1") max <- max(economic science$appointment) dp+ scale_x_date(limits = c(min, max))                  

Go further

See as well the office scale_x_datetime() and scale_y_datetime() to plot a data containing engagement and time.

Infos

This assay has been performed using R software (ver. 3.2.4) and ggplot2 (ver. )


Enjoyed this commodity? I'd be very grateful if you'd assist information technology spread by emailing information technology to a friend, or sharing it on Twitter, Facebook or Linked In.

Show me some love with the similar buttons below... Thanks and delight don't forget to share and comment below!!

Avez vous aimé cet article? Je vous serais très reconnaissant si vous aidiez à sa improvidence en 50'envoyant par courriel à un ami ou en le partageant sur Twitter, Facebook ou Linked In.

Montrez-moi un peu d'amour avec les like ci-dessous ... Merci et n'oubliez pas, s'il vous plaît, de partager et de commenter ci-dessous!