简体   繁体   中英

R - Two sets of labels on on axis in a bar plot

I have a dataframe that looks like this:

ID    Group    Measure1    Measure 2
001   A        59          559
002   A        44          623 
003   B        129         498
004   C        99          504
005   C        78          378

I want to produce a bar graph that has two sets of labels on the X-axis: one identifying each bar with its ID value, another labeling each bar by Group it belongs to. My data is set up so that members of the same group are adjacent in the dataframe.

The obvious solution of color-coding the bars by Group is not applicable because I am already using color-coding to show Measure1 and Measure2 (and in some cases Measure3). If there is another way to show the Group information besides labels, I am interested to hear it but I think that two sets of labels at the bottom of my chart is probably the best solution. Here's one such plot with only one set of labels:

图形

I would like to add the Group labels underneath the "Patient ID" labels.

If I get desperate, I will use Photoshop or Paint to add the labels but I am hoping there is a way to add a second set of labels using R.

Try:

mm = melt(ddf, id=c('ID', 'Group'))
ggplot(mm) + geom_bar(aes(x=interaction(ID, Group), y=value, group=variable, fill=variable), position='dodge', stat='identity')

在此处输入图片说明

Separator can be adjusted:

> with(ddf, interaction(ID, Group, sep="_"))
[1] 1_A 2_A 3_B 4_C 5_C
Levels: 1_A 2_A 3_A 4_A 5_A 1_B 2_B 3_B 4_B 5_B 1_C 2_C 3_C 4_C 5_C
> 
> with(ddf, interaction(ID, Group, sep=" "))
[1] 1 A 2 A 3 B 4 C 5 C
Levels: 1 A 2 A 3 A 4 A 5 A 1 B 2 B 3 B 4 B 5 B 1 C 2 C 3 C 4 C 5 C

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