jxymixer
jxymixer

Reputation: 27

How to change order in legends and change the size of legends in ggplot2

So basically, my data is like this:

1stCol 2ndCol 3rdCol

Week1  1     4

Week2  2     3

Week3  3     4

Week4  5     6

...

Week11 7     8

Week12 9     10

...


Till Week 52.

I used ggplot to plot this data:

ggplot(data, aes(b, c, colour = a)) + geom_line()

But the legends will be:

Week1 Week11 Week12... Week19 Then Week2 Week21...

But I want them be

Week1 Week2 Week3 Week4...

Is that possible?

And also, cause I have such a long list for legend, it's so hard to fit them in a jpg( I used ggsave to save it) how can I adjust to that?

Upvotes: 0

Views: 567

Answers (1)

Koundy
Koundy

Reputation: 5555

To get the legend in order convert ur column into an ordered factor like this.

data$1stCol <- factor(data$1stCol,levels=as.character(data$1stCol),ordered = TRUE)

This will preserve the order of your column. If you want to add such a large legend you can try adding legend at the bottom by adding this argument in the last.

ggplot(data, aes(b, c, colour = a)) + geom_line() + theme(legend.position="bottom")

Also you can customize the legend components including size by using various commands like

legend.background
legend.margin
legend.key
legend.key.size
legend.key.height
legend.key.width
legend.text
legend.text.align
legend.title
legend.title.align
legend.position
legend.direction

Look in ggplot2 manual pdf for examples.http://cran.r-project.org/web/packages/ggplot2/ggplot2.pdf

Upvotes: 1

Related Questions