Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make my vertical labels fit within my plotting window?

Tags:

I'm creating a histogram in R which displays the frequency of several events in a vector. Each event is represented by an integer in the range [1, 9]. I'm displaying the label for each count vertically below the chart. Here's the code:

hist(vector, axes = FALSE, breaks = chartBreaks)
axis(1, at = tickMarks, labels = eventTypes, las = 2, tick = FALSE) 

Unfortunately, the labels are too long, so they are cut off by the bottom of the window. How can I make them visible? Am I even using the right chart?

like image 583
Evan Kroske Avatar asked Nov 08 '10 22:11

Evan Kroske


2 Answers

Look at help(par), in particular fields mar (for the margin) and oma (for outer margin). It may be as simple as

par(mar=c(5,3,1,1))   # extra large bottom margin
hist(vector, axes = FALSE, breaks = chartBreaks)
axis(1, at = tickMarks, labels = eventTypes, las = 2, tick = FALSE) 
like image 62
Dirk Eddelbuettel Avatar answered Sep 22 '22 00:09

Dirk Eddelbuettel


This doesn't sound like a job for a histogram - the event is not a continuous variable. A barplot or dotplot may be more suitable.

Some dummy data

set.seed(123)
vec <- sample(1:9, 100, replace = TRUE)
vec <- factor(vec, labels = paste("My long event name", 1:9))

A barplot is produced via the barplot() function - we provide it the counts of each event using the table() function for convenience. Here we need to rotate labels using las = 2 and create some extra space of the labels in the margin

## lots of extra space in the margin for side 1
op <- par(mar = c(10,4,4,2) + 0.1)
barplot(table(vec), las = 2)
par(op) ## reset

A dotplot is produced via function dotchart() and has the added convenience of sorting out the plot margins for us

dotchart(table(vec))

The dotplot has the advantage over the barplot of using much less ink to display the same information and focuses on the differences in counts across groups rather than the magnitudes of the counts.

Note how I've set the data up as a factor. This allows us to store the event labels as the labels for the factor - thus automating the labelling of the axes in the plots. It also is a natural way of storing data like I understand you to have.

like image 33
Gavin Simpson Avatar answered Sep 23 '22 00:09

Gavin Simpson