Ordering the axis labels in geom_tile

后端 未结 5 1119
离开以前
离开以前 2020-12-28 09:31

I have a data frame containing order data for each of 20+ products from each of 20+ countries. I have put it in a highlight table using ggplot2 with code simila

5条回答
  •  时光取名叫无心
    2020-12-28 09:52

    As smillig says, the default is already to order the axes alphabetically, but the y axis will be ordered from the lower left corner up.

    The basic rule with ggplot2 that applies to almost anything that you want in a specific order is:

    • If you want something to appear in a particular order, you must make the corresponding variable a factor, with the levels sorted in your desired order.

    In this case, all you should need to do it this:

    mymelt$variable <- with(mymelt,factor(variable,levels = rev(sort(unique(variable)))))
    

    which should work regardless of whether you're running R with stringsAsFactors = TRUE or FALSE.

    This principle applies to ordering axis labels, ordering bars, ordering segments within bars, ordering facets, etc.

    For continuous variables there is a convenient scale_*_reverse() but apparently not for discrete variables, which would be a nice addition, I think.

提交回复
热议问题