Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
2 views
in R Programming by (5.3k points)

In R, how do I make a (bar)plot's y-axis labels parallel to the X-axis instead of parallel to the Y axis?

3 Answers

0 votes
by
edited by

To rotate axis labels in R, use the las argument that is a numeric value indicating the orientation of the tick mark labels and any other text added to a plot after its initialization. 

The options are as follows: 

  1. Parallel to the axis (the default, 0), 

  2. Horizontal (1), 

  3. Perpendicular to the axis (2),

  4. Vertical (3).

For example:

data(mtcars)

barplot(mtcars$cyl, col=mtcars$gear, las = 1)

Output:

image

If you want to learn more about R programming watch this tutorial on Introduction to Data Science with R 

0 votes
by (106k points)
edited by

You can rotate axis labels in R by using the below mentioned code:-

library(ggplot2) 

p <- data.frame(Day=c("2011-04-11", "2014-05-24","2004-01-12","2014-06-20","2010-08-07","2014-05-28"), Impressions=c(24010,15959,16107,21792,24933,21634),Clicks=c(211,106,248,196,160,241)) 

p

         Day Impressions Clicks 

1 2011-04-11       24010 211 

2 2014-05-24       15959 106 

3 2004-01-12       16107 248 

4 2014-06-20       21792 196 

5 2010-08-07       24933 160 

6 2014-05-28       21634 241

p$Day <- strptime(p$Day,"%Y-%m-%d") #formatting into Date  

q <- ggplot(p, aes(x=Day,y=Clicks)) + geom_line() 

q

image

q + theme(axis.text.x = element_text(angle = 60, hjust = 1))

image

By this way you can rotate labels for both X and Y axis.

0 votes
ago by (1.9k points)

For R to rotate axis labels, one usually uses the las argument in the plotting functions, or the theme function in case you are working in ggplot2. Some examples come in both base R and ggplot2 below.


Base R
Use of las argument in plot()
las = 1 gives horizontal text
las = 2 gives vertical text
las = 3 makes it perpendicular to the axis
 

a <- 1:10
b <- rnorm(10)

# Basic plot with rotated y-axis labels
plot(a, b, ylab = "Values", las = 2) # Rotate y-axis labels
 
ggplot2
In ggplot2, you can utilize the theme() function in order to change the angle of the axis labels:


library(ggplot2)
 
# Sample data
df <- data.frame(a = 1:10, b = rnorm(10))
 
# Basic ggplot with rotated x-axis labels
ggplot(df, aes(a, b)) +
geom_point() +
theme(axis.text.x = element_text(angle = 45, hjust = 1))

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 9, 2019 in R Programming by leealex956 (7.3k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...