R中的ggplot,重新排列条形

时间:2018-12-06 08:19:18

标签: r ggplot2

我有以下情节:

score = c(5,4,8,5)
Group = c('A','A','B','B')
Time = c('1','2','1','2')
df = data.frame(score,Group,Time)
df$Group = factor(df$Group)
df$Time = factor(df$Time)
a = ggplot(df, aes(x=Time, y=score, fill=Group)) + 
    geom_bar(position=position_dodge(), stat="identity", width = 0.8, color = 'black')

如何重新排列这些条形,以便将A组分组在一起,然后将B组分组,并且每个条形图的x轴分别标记为时间1,2,1,2?如下图所示:

enter image description here

1 个答案:

答案 0 :(得分:4)

在轴上具有重复元素有点违反ggplot2的工作原理。但是我们可以作弊。我建议您使用@RLave建议使用构面。但是,如果那不适合您,我会尝试不做任何尝试:

int main()
{
    srand(time(NULL));
    int randomNum = rand() % 50;
    const int guessLimit = 10;
    int usr_in;
    for(int guess = 0; guess < guessLimit; ++guess)
    {
        cout<<"Enter a number between 0 & 50: ";
        cin >> usr_in;

        if(usr_in == randomNum)
        {
            break;
        }
        else if(usr_in < randomNum)
        {
            cout<<"Guess higher"<<endl;
        }
        else
        {
            cout<< "Guess lower"<<endl;
        }
    }
    if(usr_in == randomNum)
    {
        cout<< "Correct guess you win"<< endl;
    }
    else
    {
        cout<<"You lose"<<endl;
    }
    return 0;
}

Repeated values on x-axis

如您所见,我们必须为x轴创建一个虚拟变量,然后手动将其放置在标签上。

现在考虑使用方面作为更好的解决方案

numrows=Sheets("Sheet1").Range("A1").End(xlDown).Row

使用df2 <- rbind(df, data.frame(score=NA, Group=c('A'), Time=c('9'))) df2$x <- as.character(interaction(df2$Group, df2$Time)) ggplot(df2, aes(x=x, y=score, fill=Group)) + geom_col(position='dodge', colour='black') + scale_x_discrete(labels=c('1','2','','1','2')) + theme(axis.ticks.x = element_blank(), panel.grid.major.x = element_blank()) 自变量ggplot(df, aes(x=Time, y=score, fill=Group)) + geom_col(width = 1, color = 'black') + facet_grid(~Group) + theme(strip.background = element_blank(), strip.text = element_blank(), panel.spacing.x=grid::unit(3, 'pt')) 调整面板之间的距离。

enter image description here