2

I have this dataframe:

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'}})

Where I plot this:

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

enter image description here

I'm looking to change the position of the legends to the same to the positions of the plot: blue-up and red-bottom. And A always will be red and B always will be blue

Chris
  • 2,019
  • 5
  • 22
  • 67

2 Answers2

1

There might be a more standard way to do it, but here is a quick hack to fix your problem:

  1. Change the order of your variable

  2. Assign colors manually (You could also look for exact color codes and replace it with the color names if it matters in your case)

     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"]))
    

output looks like this:

enter image description here

Ehsan
  • 12,072
  • 2
  • 20
  • 33
0

You could set order of levels with df$variable <- factor(df$variable, levels = c("B","A")

  • Python doesn't work with levels as in R. However, if I change the order in the data, blue is going to be down where it should be go up. – Chris Mar 18 '20 at 13:19