如何在ggplot2 R中根据另一个图例订购一个图例?

时间:2019-04-18 20:11:51

标签: r ggplot2

我有两个不同的数据集,但标签名称相同。在绘制完两个图后,我发现图例的顺序不同,颜色也不同。想知道我该怎么做以确保它们一致吗?

enter image description here

非常感谢您!

1 个答案:

答案 0 :(得分:1)

您可以使用#include <iostream> struct Coord_2D { size_t x = 0; size_t y = 0; }; Coord_2D index_to_coords(size_t index, const Coord_2D& dimensions) { return {index % dimensions.x, index / dimensions.x}; } size_t coords_to_index(const Coord_2D& coords, const Coord_2D& dimensions) { return coords.y * dimensions.x + coords.x; } int main() { Coord_2D dimensions = {50, 50}; std::string arr(dimensions.x * dimensions.y, '0'); // "zero" the array; // alter the element at (23, 31) for the sake of example arr[coords_to_index({23, 31}, dimensions)] = 'F'; std::cout << arr << std::endl; } 来设置两个数据集中factorlevels的顺序。

labels

结果: enter image description here enter image description here

样本数据:

require(tidyverse)

df1 %>% 
  mutate(cyl = factor(
    cyl, 
    levels = c("4", "6", "8"), 
    labels = c("Four", "Six", "Eight"))) %>% 
  ggplot(aes(disp, drat, color = cyl)) + 
  geom_point()

df2 %>% 
  mutate(cyl = factor(
    cyl, 
    levels = c("4", "6", "8"), 
    labels = c("Four", "Six", "Eight"))) %>% 
  ggplot(aes(disp, drat, color = cyl)) + 
  geom_point()