无法将图例添加到ggplot

时间:2019-12-07 22:28:03

标签: r ggplot2

我正在尝试向ggplot添加图例,这就是我尝试过的内容(数据只是3个简单的数字列。)

       JFrame frame = new JFrame();  

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setBackground(Color.black);

        JPanel panel = new JPanel();
        panel.setBackground(Color.WHITE);

        frame.getContentPane().add(panel);
        JPanel panel_1 = new JPanel();

        panel_1.setPreferredSize(new Dimension(200, 200));
        panel_1.setBackground(Color.red); 

        panel.add(panel_1);

        //FlowLayout.RIGHT, LEFT, CENTER
        panel.setLayout(new FlowLayout(FlowLayout.RIGHT)); 

        frame.setSize(800,800); 
        frame.setVisible(true);

数据示例,例如:

ggplot(data, aes(x = instant, y = cnt))+
  geom_point(aes(instant, cnt), color = rgb(0.45,0.63,0.76, 0.7))+
  geom_point(aes(instant, registered), color = rgb(0.70,0.52,0.75, 0.5))+
  geom_point(aes(instant, casual), color = rgb(0.95,0.61,0.73, 0.5))+
  theme(legend.position="right")

哪个cnt是已注册和临时的总和,即时是索引号。

the 3 colors represents different variables, and I would like to label them in the legend. 它没有按我预期的那样工作。我只知道legend()可在plot()中使用,所以如何在ggplot中添加图例?

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

data <- data.frame(matrix(c(1,2,3,3,5,9,1,2,4,2,3,5),3,4))
colnames(data) <- c("instant", "cnt", "registered", "casual")

您需要将其设置为长格式,但首先我们设置颜色:

COLS = c(rgb(0.45,0.63,0.76, 0.7),rgb(0.70,0.52,0.75, 0.5),rgb(0.95,0.61,0.73, 0.5))
names(COLS) = c("cnt","registered","casual")

然后使用tidyr使其变长:

library(tidyr)

data %>% 
pivot_longer(-instant) %>% 
ggplot(aes(x=instant,y=value,col=name)) + 
geom_point() +
scale_color_manual(values=COLS)

enter image description here