2

我有这个数据框:

df = pd.DataFrame({'ymin': {0: 0.0,
  1: 0.0,
  2: 0.0,
  3: 0.0,
  4: 0.511,
  5: 0.571,
  6: 0.5329999999999999,
  7: 0.5389999999999999},
 'ymax': {0: 0.511,
  1: 0.571,
  2: 0.533,
  3: 0.539,
  4: 1.0,
  5: 1.0,
  6: 1.0,
  7: 1.0},
 'xmin': {0: 0.0,
  1: 0.14799999999999996,
  2: 0.22400000000000003,
  3: 0.5239999999999999,
  4: 0.0,
  5: 0.14799999999999996,
  6: 0.22400000000000003,
  7: 0.5239999999999999},
 'xmax': {0: 0.148,
  1: 0.22399999999999998,
  2: 0.524,
  3: 1.001,
  4: 0.148,
  5: 0.22399999999999998,
  6: 0.524,
  7: 1.001},
 'variable': {0: 'A', 1: 'A', 2: 'A', 3: 'A', 4: 'B', 5: 'B', 6: 'B', 7: 'B'}})

我在哪里绘制这个:

(ggplot(df, aes(ymin = "ymin", ymax = "ymax",
     xmin = "xmin", xmax = "xmax", fill = "variable"))
 + geom_rect(colour = "grey", alpha=0.7))

在此处输入图像描述

我希望将图例的位置更改为与情节的位置相同:蓝色向上和红色底部。永远A是红色的,B永远是蓝色的

4

2 回答 2

1

可能有一种更标准的方法来做到这一点,但这里有一个快速解决问题的方法:

  1. 更改变量的顺序

  2. 手动分配颜色(如果对您的情况很重要,您也可以查找确切的颜色代码并将其替换为颜色名称)

     df = df.assign(variable = pd.Categorical(df['variable'], ['B', 'A']))
    
     (ggplot(df, aes(ymin = "ymin", ymax = "ymax",
         xmin = "xmin", xmax = "xmax", fill = "variable"))+
         geom_rect(colour = "grey", alpha=0.7)+
         scale_fill_manual(values = ["blue", "red"]))
    

输出如下所示:

在此处输入图像描述

于 2020-04-04T05:17:02.807 回答
0

您可以设置级别的顺序df$variable <- factor(df$variable, levels = c("B","A")

于 2020-03-18T03:29:35.830 回答