使用log-y刻度覆盖直方图的颜色填充不正确

时间:2015-05-01 16:55:47

标签: r ggplot2

我试图覆盖两个直方图并以对数刻度绘制其y轴。一些示例代码:

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;

@SuppressWarnings("serial")
public class RadioEg extends JPanel {
   private static final String[] RADIO_TEXTS = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
   private ButtonGroup buttonGroup = new ButtonGroup();

   public RadioEg() {
      JPanel radioPanel = new JPanel(new GridLayout(0, 1));
      for (String radioText : RADIO_TEXTS) {
         JRadioButton radioButton = new JRadioButton(radioText);
         radioButton.setActionCommand(radioText); // set this!
         radioPanel.add(radioButton); // add to JPanel
         buttonGroup.add(radioButton); // add to button group
      }

      JPanel southPanel = new JPanel();
      southPanel.add(new JButton(new AbstractAction("GetSelection") {

         @Override
         public void actionPerformed(ActionEvent e) {
            ButtonModel buttonModel = buttonGroup.getSelection();
            if (buttonModel != null) {
               String actionCommand = buttonModel.getActionCommand();
               System.out.println("Selected Button: " + actionCommand);
            }
         }
      }));

      setLayout(new BorderLayout());
      add(radioPanel, BorderLayout.CENTER);
      add(southPanel, BorderLayout.PAGE_END);
   }

   private static void createAndShowGui() {
      JFrame frame = new JFrame("RadioEg");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(new RadioEg());
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

如果没有设置dat1<- data.frame( x = rpois(1000, 50), y = rep("X1", 1000) ) dat2<- data.frame( x = rpois(1000, 30), y = rep("X0", 1000) ) dat<- rbind(dat1, dat2) p <- ggplot(dat, aes(x = x, fill = y)) + geom_histogram( aes(y=..density..), breaks= seq( min(dat$x), max(dat$x),(max(dat$x)-min(dat$x))/30 ), alpha=0.4, position="identity", lwd=0.2 ) + scale_y_log10() + scale_fill_manual(values=c("red", "black"), labels=c("X1", "X0")) print(p) ,我会得到类似的结果:

enter image description here

然而,使用scale_y_log10()后,直方图颜色未正确填充(参见下文,两个直方图的重叠未填充颜色,而是填充空白区域)。任何想法如何解决这个问题?

enter image description here

1 个答案:

答案 0 :(得分:1)

使用:

ggplot(dat) +
  geom_histogram(aes(x=x, y=log10(..density.. + 1), fill=y), alpha=0.4, position="identity", lwd=0.2) + 
  scale_fill_manual(values=c("red", "black"), labels=c("X1", "X0"))
你得到: enter image description here

一些解释:现在你的情节中有x个值为零。这在进行日志转换时会出现一些问题。通过添加1,您可以在对数刻度中包含零。