コード例 #1
0
    def __init__(self, width, height, range):
        JPanel()
        plot = MeterPlot(DefaultValueDataset(0))
        self.plot = plot
        self.setRange(range)
        #plot.addInterval(MeterInterval("Normal", Range(0.0, 35.0),
        #        Color.lightGray, BasicStroke(2.0),
        #        Color(0, 255, 0, 64)))
        #plot.addInterval(MeterInterval("Warning", Range(35.0, 50.0),
        #        Color.lightGray, BasicStroke(2.0), Color(255, 255, 0, 64)))
        #plot.addInterval(MeterInterval("Critical", Range(50.0, 60.0),
        #        Color.lightGray, BasicStroke(2.0),
        #        Color(255, 0, 0, 128)))
        plot.setNeedlePaint(Color.darkGray)
        plot.setDialBackgroundPaint(Color.white)
        plot.setDialOutlinePaint(Color.white)
        plot.setDialShape(DialShape.CHORD)
        plot.setMeterAngle(260)
        plot.setTickLabelsVisible(True)
        plot.setTickLabelFont(Font("Dialog", Font.BOLD, 10))
        plot.setTickLabelPaint(Color.darkGray)
        plot.setTickSize(5.0)
        plot.setTickPaint(Color.lightGray)

        plot.setValuePaint(Color.black)
        plot.setValueFont(Font("Dialog", Font.BOLD, 14))
        plot.setUnits("k sims")

        chart = JFreeChart("Simulations computed",
                           JFreeChart.DEFAULT_TITLE_FONT, plot, False)
        self.chart = chart
        chart.setBackgroundPaint(Color.white)
        cp = ChartPanel(chart)
        cp.setPreferredSize(Dimension(width, height))
        self.add(cp)
コード例 #2
0
ファイル: Meter.py プロジェクト: samitha/lositan
    def __init__(self, width, height, range):
        JPanel()
        plot = MeterPlot(DefaultValueDataset(0))
        self.plot = plot
        self.setRange(range)
        #plot.addInterval(MeterInterval("Normal", Range(0.0, 35.0),
        #        Color.lightGray, BasicStroke(2.0),
        #        Color(0, 255, 0, 64)))
        #plot.addInterval(MeterInterval("Warning", Range(35.0, 50.0),
        #        Color.lightGray, BasicStroke(2.0), Color(255, 255, 0, 64)))
        #plot.addInterval(MeterInterval("Critical", Range(50.0, 60.0),
        #        Color.lightGray, BasicStroke(2.0),
        #        Color(255, 0, 0, 128)))
        plot.setNeedlePaint(Color.darkGray)
        plot.setDialBackgroundPaint(Color.white)
        plot.setDialOutlinePaint(Color.white)
        plot.setDialShape(DialShape.CHORD)
        plot.setMeterAngle(260)
        plot.setTickLabelsVisible(True)
        plot.setTickLabelFont(Font("Dialog", Font.BOLD, 10));
        plot.setTickLabelPaint(Color.darkGray)
        plot.setTickSize(5.0)
        plot.setTickPaint(Color.lightGray)

        plot.setValuePaint(Color.black)
        plot.setValueFont(Font("Dialog", Font.BOLD, 14));
        plot.setUnits("k sims")

        chart = JFreeChart("Simulations computed",
                JFreeChart.DEFAULT_TITLE_FONT, plot, False)
        self.chart = chart
        chart.setBackgroundPaint(Color.white)
        cp = ChartPanel(chart)
        cp.setPreferredSize(Dimension(width, height))
        self.add(cp)
コード例 #3
0
 def __init__(self, width, height, isTemporal=False):
     JPanel()
     self.isTemporal = isTemporal
     self.minY = 0.0  # -0.05
     self.minX = 0.0  # -0.02
     self.maxX = 0.5  # 0.52
     self.maxY = 1.0
     self.drawCI = False
     if isTemporal:
         self.title = "Fgt/Hs"
     else:
         self.title = "Fst/He"
     self.labelSelected = True
     self.labelNeutral = False
     self.posColor = Color.RED
     self.neuColor = Color.LIGHT_GRAY
     self.balColor = Color.YELLOW
     self.markerColor = Color.BLUE
     self.exportX = width
     self.exportY = height
     self.chart = self._createEmptyChart()
     self.chart.setAntiAlias(True)
     self.resetData()
     self.cp = ChartPanel(self.chart)
     self.cp.setDisplayToolTips(True)
     self.cp.setPreferredSize(Dimension(width, height))
     self.add(self.cp)
コード例 #4
0
ファイル: Chart.py プロジェクト: tiagoantao/lositan
 def __init__(self, width, height, isTemporal=False):
     JPanel()
     self.isTemporal = isTemporal
     self.minY = 0.0  # -0.05
     self.minX = 0.0  # -0.02
     self.maxX = 0.5  # 0.52
     self.maxY = 1.0
     self.drawCI = False
     if isTemporal:
         self.title = "Fgt/Hs"
     else:
         self.title = "Fst/He"
     self.labelSelected = True
     self.labelNeutral = False
     self.posColor = Color.RED
     self.neuColor = Color.LIGHT_GRAY
     self.balColor = Color.YELLOW
     self.markerColor = Color.BLUE
     self.exportX = width
     self.exportY = height
     self.chart = self._createEmptyChart()
     self.chart.setAntiAlias(False)
     self.resetData()
     self.cp = ChartPanel(self.chart)
     self.cp.setDisplayToolTips(True)
     self.cp.setPreferredSize(Dimension(width, height))
     self.add(self.cp)
コード例 #5
0
	def generatePlotPanel(self, plotTitle, listData, showLegend, showTooltip):
		"""
		1) Create a PieDataset
		2) Create a PieChart (or  Create a PiePlot and put it in a JFreeChart)
		3) Put the PieChart in a ChartPanel
		"""
		# Get a dictionary of value occurence in the list {value1:count, value2:count...}
		dataDico = Counter(listData)
		#print dataDico # value: counts OK
		 
		# Create a Pie dataset from the dicoData
		pieDataset = DefaultPieDataset() 
		for key, value in dataDico.items(): 
			#print key, value 
			pieDataset.setValue(key, value) 
				 
		# Create an instance of JFreeChart 	
		urls = False
		chart = ChartFactory.createPieChart(plotTitle, pieDataset, showLegend, showTooltip, urls) 
		
		# Alternative way
		#piePlot = PiePlot(pieDataset)
		#chart   = JFreeChart(plotTitle, piePlot)
		
		return ChartPanel(chart)
コード例 #6
0
ファイル: vis.py プロジェクト: Bloodevil/socialite
    def plot(self):
        chart = self.createChart()
        plot = chart.getXYPlot()
        if self.logx:
            logx = LogarithmicAxis("Log("+xlabel()+")")
            plot.setDomainAxis(logx)
        if self.logy:
            logy = LogarithmicAxis("Log("+ylabel()+")")
            plot.setRangeAxis(logy)

        chartPanel = ChartPanel(chart)
        chartPanel.setPreferredSize(java.awt.Dimension(self._size[0], self._size[1]))
        self.setContentPane(chartPanel)

        self.pack()
        self.setVisible(True)
コード例 #7
0
    def __init__(self, automations):

        # Create the frame
        frame = JFrame("Automation Viewer")
        frame.setSize(500, 300)
        frame.setLayout(BorderLayout())

        series = AutomationSeries
        # Finalize the window
        frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE)
        frame.setVisible(True)

        # Create an XY dataset
        dataset = XYSeriesCollection()

        for autoname in automations:

            automation = ModbusPal.getAutomation(autoname)
            series = AutomationSeries(automation)
            dataset.addSeries(series)
            frame.addWindowListener(series)

        # Create chart
        chart = ChartFactory.createXYLineChart("Automation Viewer",
                                               "Time (seconds)", "Value",
                                               dataset,
                                               PlotOrientation.VERTICAL,
                                               Boolean.TRUE, Boolean.TRUE,
                                               Boolean.FALSE)
        panel = ChartPanel(chart)

        # Add chart to panel
        frame.add(panel, BorderLayout.CENTER)
コード例 #8
0
    def plot(self):
        chart = self.createChart()
        plot = chart.getXYPlot()
        if self.logx:
            logx = LogarithmicAxis("Log(" + xlabel() + ")")
            plot.setDomainAxis(logx)
        if self.logy:
            logy = LogarithmicAxis("Log(" + ylabel() + ")")
            plot.setRangeAxis(logy)

        chartPanel = ChartPanel(chart)
        chartPanel.setPreferredSize(
            java.awt.Dimension(self._size[0], self._size[1]))
        self.setContentPane(chartPanel)

        self.pack()
        self.setVisible(True)
コード例 #9
0
    def show(self, size=(500, 500)):
        panel = ChartPanel(self.chart)

        def onclose(e):
            e.getWindow().dispose()
            self.dispose()

        frame = swing.JFrame(windowClosing=onclose)
        frame.setContentPane(panel)
        frame.size = size
        frame.visible = True
        self.frame = frame
コード例 #10
0
 def __init__(self):
     """ generated source for method __init__ """
     super(ConfigurableDetailPanel, self).__init__(GridBagLayout())
     model = DefaultTableModel()
     model.addColumn("Step")
     model.addColumn("My Move")
     model.addColumn("Time spent")
     model.addColumn("Out of time?")
     self.moveTable = JZebraTable(model)
     self.moveTable.setShowHorizontalLines(True)
     self.moveTable.setShowVerticalLines(True)
     sidePanel = JPanel()
     self.memUsage = TimeSeries("Used Memory")
     self.memTotal = TimeSeries("Total Memory")
     self.memUsage.setMaximumItemCount(36000)
     self.memTotal.setMaximumItemCount(36000)
     memory = TimeSeriesCollection()
     memory.addSeries(self.memUsage)
     memory.addSeries(self.memTotal)
     memChart = ChartFactory.createTimeSeriesChart(None, None, "Megabytes", memory, True, True, False)
     memChart.setBackgroundPaint(getBackground())
     memChartPanel = ChartPanel(memChart)
     memChartPanel.setPreferredSize(Dimension(500, 175))
     sidePanel.add(memChartPanel)
     self.counters = HashSet()
     self.countersCollection = TimeSeriesCollection()
     counterChart = ChartFactory.createTimeSeriesChart(None, None, None, self.countersCollection, True, True, False)
     counterChart.getXYPlot().setRangeAxis(LogarithmicAxis("Count per 100ms"))
     counterChart.getXYPlot().getRangeAxis().setAutoRangeMinimumSize(1.0)
     counterChart.setBackgroundPaint(getBackground())
     counterChartPanel = ChartPanel(counterChart)
     counterChartPanel.setPreferredSize(Dimension(500, 175))
     sidePanel.add(counterChartPanel)
     self.scoreCountersCollection = TimeSeriesCollection()
     scoreCounterChart = ChartFactory.createTimeSeriesChart(None, None, "Score", self.scoreCountersCollection, True, True, False)
     scoreCounterChart.getXYPlot().getRangeAxis().setRange(0, 100)
     scoreCounterChart.setBackgroundPaint(getBackground())
     scoreCounterChartPanel = ChartPanel(scoreCounterChart)
     scoreCounterChartPanel.setPreferredSize(Dimension(500, 175))
     sidePanel.add(scoreCounterChartPanel)
     self.add(JScrollPane(self.moveTable, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED), GridBagConstraints(0, 0, 1, 2, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, Insets(0, 0, 0, 0), 0, 0))
     self.add(sidePanel, GridBagConstraints(1, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, Insets(0, 0, 0, 0), 0, 0))
     self.add(JButton(resetButtonMethod()), GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, GridBagConstraints.SOUTHEAST, GridBagConstraints.NONE, Insets(0, 0, 0, 0), 0, 0))
コード例 #11
0
def plot(geoms, size=(500, 500)):
    """
  Plots a set of geometry objects into a xy grid.

  *geom* is a `list` of geometry objects to plot. *size* is the resulting
  size of the rendered plot.
  """

    if not isinstance(geoms, list):
        geoms = [geoms]

    gd = GeometryDataset(geoms)
    plot = gd.createPlot()
    chart = JFreeChart(plot)
    panel = ChartPanel(chart)

    frame = swing.JFrame()
    frame.setContentPane(panel)
    frame.size = size
    frame.visible = True
コード例 #12
0
ファイル: plot.py プロジェクト: mwinding/scripts
def renderHistogram(values,
                    n_bins,
                    min_max=None,
                    title="Histogram",
                    color=Color.red,
                    show=True,
                    setThemeFn=setTheme):
    """ values: a list or array of numeric values.
      n_bins: the number of bins to use.
      min_max: defaults to None, a tuple with the minimum and maximum value.
      title: defaults to "Histogram", must be not None.
      show: defaults to True, showing the histogram in a new window.
      setThemeFn: defaults to setTheme, can be None or another function that takes a chart
               as argument and sets rendering colors etc.
      Returns a tuple of the JFreeChart instance and the window JFrame, if shown.
  """
    hd = HistogramDataset()
    hd.setType(HistogramType.RELATIVE_FREQUENCY)
    print min_max
    if min_max:
        hd.addSeries(title, values, n_bins, min_max[0], min_max[1])
    else:
        hd.addSeries(title, values, n_bins)
    chart = ChartFactory.createHistogram(title, "", "", hd,
                                         PlotOrientation.VERTICAL, False,
                                         False, False)
    # Adjust series color
    chart.getXYPlot().getRendererForDataset(hd).setSeriesPaint(0, color)
    #
    if setThemeFn:
        setThemeFn(chart)
    frame = None
    if show:
        frame = JFrame(title)
        frame.getContentPane().add(ChartPanel(chart))
        frame.pack()
        frame.setVisible(True)
    return chart, frame
コード例 #13
0
	def generatePlotPanel(self, plotTitle, listData):
		"""
		1) Create a CategoryDataset
		2) Create a BarChart (or  Create a BarPlot and put it in a JFreeChart)
		3) Put the BarChart in a ChartPanel
		"""
		# Get a dictionary of value occurence in the list {value1:count, value2:count...}
		dataDico = Counter(listData)
		#print dataDico # value: counts OK
		 
		# Create a Pie dataset from the dicoData
		dataset = DefaultCategoryDataset() 
		for key, value in dataDico.items(): 
			#print key, value 
			dataset.setValue(value, key, "") 
		
		# Create an instance of JFreeChart 	
		chart = ChartFactory.createBarChart(plotTitle, "Categories", "Count", dataset) 
		# Alternative way
		#piePlot = PiePlot(pieDataset)
		#chart   = JFreeChart(plotTitle, piePlot)
		
		return ChartPanel(chart)
コード例 #14
0
def plot(geoms, size=(500,500)):
  """
  Plots a set of geometry objects into a xy grid.

  *geom* is a `list` of geometry objects to plot. *size* is the resulting
  size of the rendered plot.
  """

  if not isinstance(geoms, list):
    geoms = [geoms]

  data = GeometryDataset(geoms)
  r = GeometryRenderer()
  #r.setFillPolygons(True)

  plot = XYPlot(data, data.getDomain(), data.getRange(), r);
  chart = JFreeChart(plot)
  panel = ChartPanel(chart)
  
  frame = swing.JFrame()
  frame.setContentPane(panel)
  frame.size = size
  frame.visible = True
コード例 #15
0
class Chart(JPanel):
    def _createEmptyChart(self, dataset=None):
        if self.isTemporal:
            hText = "Hs"
            fText = "Fgt"
        else:
            hText = "He"
            fText = "Fst"
        chart = ChartFactory.createXYLineChart(
            self.title,  # chart title
            hText,  # x axis label
            fText,  # y axis label
            dataset,  # data
            PlotOrientation.VERTICAL,
            True,  # include legend
            True,  # tooltips
            False  # urls
        )
        chart.setBackgroundPaint(Color.white)
        # get a reference to the plot for further customisation...
        # change the auto tick unit selection to integer units only...
        #rangeAxis = plot.getRangeAxis()
        #rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits())
        self.confArea = None
        return chart

    def setSelLoci(self, pv, allLoci, selLoci):
        self.pv = pv
        self.allLoci = allLoci
        self.selLoci = selLoci
        self.drawLabels()

    def drawLabels(self):
        if not hasattr(self, 'pv'): return
        plot = self.chart.getPlot()
        plot.clearAnnotations()
        red = 0
        for i in range(len(self.valMarkers)):
            if not self.valMarkers[i]:
                red += 1
                continue
            if self.allLoci[i] in self.selLoci:
                if not self.labelSelected: continue
            else:
                if not self.labelNeutral: continue

            x = self.pv[i - red][0]
            y = self.pv[i - red][1]
            locus = self.allLoci[i]
            note = XYTextAnnotation(locus, x + 0.002, y + 0.002)
            note.setTextAnchor(TextAnchor.BOTTOM_LEFT)
            plot.addAnnotation(note)

    def setMarkers(self, markers):
        self.markers = XYSeries("Markers")
        self.maxX = 0.0
        self.maxY = 0.0
        self.minY = -0.05
        self.out = []
        self.valMarkers = markers
        for marker in markers:
            if not marker:
                continue
            if marker[0] < 2 and marker[0] > self.maxX:
                self.maxX = marker[0]
            if marker[1] < 2 and marker[1] > self.maxY:
                self.maxY = marker[1]
            if marker[1] > -2 and marker[1] < self.minY:
                self.minY = marker[1]

            #self.markers.add(marker[0], max([0.0, marker[1]]))
            self.markers.add(marker[0], marker[1])
        self.maxX = max([0.501, self.maxX + 0.001])
        self.maxX = min([1, self.maxX])
        self.maxY += 0.05
        self.minY -= 0.05

    def setTop(self, markers):
        #setBottom has to be done before, as setMarkers
        self.top = YIntervalSeries("Candidate neutral")
        self.limit = YIntervalSeries("Candidate positive selection")
        if len(markers) > 1:
            #if self.maxY > markers[0][1]:
            #    self.limit.add(0.0, markers[0][1], markers[0][0], markers[0][1])
            #else: #It does not really matter
            #    self.limit.add(0.0, -1, 1.1, 1.1)
            self.limit.add(0.0, markers[0][1], markers[0][1], 1.1)
        for i in range(len(markers)):
            self.top.add(markers[i][0], self.bottomList[i][1],
                         self.bottomList[i][1], markers[i][1])
            if self.maxY > markers[i][1]:
                self.limit.add(markers[i][0], markers[i][1], markers[i][1],
                               1.1)
            else:  #It does not really matter
                self.limit.add(markers[i][0], markers[i][1], markers[i][1],
                               1.1)
            #if markers[i][0] > self.maxX: break
            #We do this at the end to fill the whole graphic

    def setBottom(self, markers):
        #print markers
        self.bottomList = map(lambda (x, y): (x, y),
                              markers)  #legacy, can remove...
        self.bottom = YIntervalSeries("Candidate balancing selection")
        if len(markers) > 0:
            self.bottom.add(0.0, -1.0, -1.0, self.bottomList[0][1])
        for marker in self.bottomList:
            self.bottom.add(marker[0], -1.0, -1.0, marker[1])
            #if marker[0] > self.maxX: break
            #We do this at the end to fill the whole graphic

    def updateChartDataset(self, drawLabels=True):
        dataset = XYSeriesCollection()
        #self._calculateConfArea()
        #dataset.addSeries(self.confArea)
        dataset.addSeries(self.markers)
        plot = self.chart.getPlot()
        rangeAxis = plot.getRangeAxis()
        domainAxis = plot.getDomainAxis()
        rangeAxis.setRange(self.minY, self.maxY)  #change
        domainAxis.setRange(self.minX, self.maxX)
        #plot.setBackgroundPaint(Color.lightGray);
        #plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
        #plot.setDomainGridlinePaint(Color.white);
        #plot.setRangeGridlinePaint(Color.white);

        markerRenderer = XYLineAndShapeRenderer(False, True)
        #print self.markerColor
        markerRenderer.setSeriesPaint(0, self.markerColor)
        markerRenderer.setSeriesShape(0, Ellipse2D.Double(-3, -3, 6, 6))
        #markerRenderer.setToolTipGenerator(FDistToolTipGenerator(self.pointNames))
        plot.setRenderer(0, markerRenderer)
        plot.setDataset(0, dataset)
        dataset = XYSeriesCollection()
        if self.drawCI:
            dataset = YIntervalSeriesCollection()
            CIRenderer = DeviationRenderer(True, False)
            # CIRenderer.setOutline(True)
            # CIRenderer.setRoundXCoordinates(True)
            dataset.addSeries(self.bottom)
            dataset.addSeries(self.top)
            dataset.addSeries(self.limit)
            CIRenderer.setSeriesFillPaint(0, self.balColor)
            CIRenderer.setSeriesFillPaint(1, self.neuColor)
            CIRenderer.setSeriesFillPaint(2, self.posColor)
            CIRenderer.setSeriesPaint(0, self.balColor)
            CIRenderer.setSeriesPaint(1, self.neuColor)
            CIRenderer.setSeriesPaint(2, self.posColor)
            plot.setDataset(1, dataset)
            plot.setRenderer(1, CIRenderer)
        plot.setDataset(1, dataset)
        if drawLabels:
            self.drawLabels()

    def resetData(self, justAnnots=False):
        if not justAnnots:
            self.markers = XYSeries("Markers")
        self.drawCI = False
        self.chart.getPlot().clearAnnotations()
        if hasattr(self, 'pv'):
            del (self.pv)
        self.updateChartDataset()

    def save(self, parent, format):
        chooser = JFileChooser()
        # filter = FileNameExtensionFilter(
        #     format + " files",
        #     array([format, format.lower()], String))
        # chooser.setFileFilter(filter);
        returnVal = chooser.showSaveDialog(parent)
        if returnVal == JFileChooser.APPROVE_OPTION:
            fileName = chooser.getSelectedFile().getPath()
            if not fileName.upper().endswith('.' + format):
                fileName += '.' + format.lower()
            file = File(fileName)
        else:
            return
        if format == 'PNG':
            ChartUtils.saveChartAsPNG(file, self.chart, self.exportX,
                                      self.exportY)
        elif format == 'SVG':
            domImpl = GenericDOMImplementation.getDOMImplementation()
            doc = domImpl.createDocument(None, "svg", None)
            svgGen = SVGGraphics2D(doc)
            svgGen.getGeneratorContext().setPrecision(6)
            self.chart.draw(
                svgGen, Rectangle2D.Double(0, 0, self.exportX, self.exportY),
                None)
            out = OutputStreamWriter(FileOutputStream(file), "UTF-8")
            svgGen.stream(out, True)  #True is for useCSS
            out.close()
        elif format == 'PDF':
            mapper = DefaultFontMapper()
            pageSize = Rectangle(self.exportX, self.exportY)
            doc = TextDocument(pageSize, 50, 50, 50, 50)
            out = BufferedOutputStream(FileOutputStream(file))
            writer = PdfWriter.getInstance(doc, out)
            doc.open()
            cb = writer.getDirectContent()
            tp = cb.createTemplate(self.exportX, self.exportY)
            g2 = tp.createGraphics(self.exportX, self.exportY, mapper)
            r2D = Rectangle2D.Double(0, 0, self.exportX, self.exportY)
            self.chart.draw(g2, r2D)
            g2.dispose()
            cb.addTemplate(tp, 0, 0)
            doc.close()
            #out.close()

    def __init__(self, width, height, isTemporal=False):
        JPanel()
        self.isTemporal = isTemporal
        self.minY = 0.0  # -0.05
        self.minX = 0.0  # -0.02
        self.maxX = 0.5  # 0.52
        self.maxY = 1.0
        self.drawCI = False
        if isTemporal:
            self.title = "Fgt/Hs"
        else:
            self.title = "Fst/He"
        self.labelSelected = True
        self.labelNeutral = False
        self.posColor = Color.RED
        self.neuColor = Color.LIGHT_GRAY
        self.balColor = Color.YELLOW
        self.markerColor = Color.BLUE
        self.exportX = width
        self.exportY = height
        self.chart = self._createEmptyChart()
        self.chart.setAntiAlias(True)
        self.resetData()
        self.cp = ChartPanel(self.chart)
        self.cp.setDisplayToolTips(True)
        self.cp.setPreferredSize(Dimension(width, height))
        self.add(self.cp)
コード例 #16
0
from ij import IJ
from org.jfree.chart import ChartFactory, ChartPanel
from org.jfree.data.statistics import HistogramDataset, HistogramType
from javax.swing import JFrame
from java.awt import Color

imp = IJ.getImage()
pixels = imp.getProcessor().convertToFloat().getPixels()

# Data and parameter of the histogram
values = list(pixels)
n_bins = 256 # number of histogram bins

# Construct the histogram from the pixel data
hist = HistogramDataset()
hist.setType(HistogramType.RELATIVE_FREQUENCY)
hist.addSeries("my data", values, n_bins)

# Create a JFreeChart histogram
chart = ChartFactory.createHistogram("My histogram", "the bins", "counts", hist)

# Adjust series color
chart.getXYPlot().getRendererForDataset(hist).setSeriesPaint(0, Color.blue)

# Show the histogram in an interactive window
# where the right-click menu enables saving to PNG or SVG, and adjusting properties
frame = JFrame("Histogram window")
frame.getContentPane().add(ChartPanel(chart))
frame.pack()
frame.setVisible(True)
コード例 #17
0
ファイル: Chart.py プロジェクト: samitha/lositan
class Chart(JPanel):
    def _createEmptyChart(self, dataset = None):
        chart = ChartFactory.createXYLineChart(
            self.title,               # chart title
            "He",                     # x axis label
            "Fst",                    # y axis label
            dataset,                  # data
            PlotOrientation.VERTICAL,
            True,                     # include legend
            True,                     # tooltips
            False                     # urls
        )
        chart.setBackgroundPaint(Color.white)
        # get a reference to the plot for further customisation...
        # change the auto tick unit selection to integer units only...
        #rangeAxis = plot.getRangeAxis()
        #rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits())
        self.confArea = None
        return chart

    def setSelLoci(self, pv, allLoci, selLoci):
        self.pv = pv
        self.allLoci = allLoci
        self.selLoci = selLoci
        self.drawLabels()

    def drawLabels(self):
        if not hasattr(self, 'pv'): return
        plot = self.chart.getPlot()
        plot.clearAnnotations()
        red = 0
        for i in range(len(self.valMarkers)):
            if not self.valMarkers[i]:
                red += 1
                continue
            if self.allLoci[i] in self.selLoci:
                if not self.labelSelected: continue
            else:
                if not self.labelNeutral: continue

            x = self.pv[i-red][0]
            y = self.pv[i-red][1]
            locus = self.allLoci[i]
            note = XYTextAnnotation(locus, x + 0.002, y + 0.002)
            note.setTextAnchor(TextAnchor.BOTTOM_LEFT)
            plot.addAnnotation(note)


    def setMarkers(self, markers):
        self.markers = XYSeries("Markers")
        self.maxX = 0.0
        self.maxY = 0.0
        self.minY = -0.05
        self.out = []
        self.valMarkers = markers
        for marker in markers:
            if not marker:
                continue
            if marker[0]<2 and marker[0] > self.maxX:
                self.maxX = marker[0]
            if marker[1]<2 and marker[1] > self.maxY:
                self.maxY = marker[1]
            if marker[1]>-2 and marker[1] < self.minY:
                self.minY = marker[1]

            #self.markers.add(marker[0], max([0.0, marker[1]]))
            self.markers.add(marker[0], marker[1])
        self.maxX += 0.1
        self.maxX = min([1, self.maxX])
        self.maxY += 0.05
        self.minY -= 0.05

    def setTop(self, markers):
        #setBottom has to be done before, as setMarkers
        self.top = YIntervalSeries("Candidate neutral")
        self.limit = YIntervalSeries("Candidate positive selection")
        if len(markers) > 1:
            #if self.maxY > markers[0][1]:
            #    self.limit.add(0.0, markers[0][1], markers[0][0], markers[0][1])
            #else: #It does not really matter
            #    self.limit.add(0.0, -1, 1.1, 1.1)
            self.limit.add(0.0, markers[0][1], markers[0][1], 1.1)
        for i in range(len(markers)):
            self.top.add(markers[i][0], self.bottomList[i][1],self.bottomList[i][1],
                markers[i][1] )
            if self.maxY > markers[i][1]:
                self.limit.add(markers[i][0], markers[i][1],markers[i][1],
                    1.1)
            else: #It does not really matter
                self.limit.add(markers[i][0], markers[i][1],markers[i][1], 1.1)
            #if markers[i][0] > self.maxX: break
            #We do this at the end to fill the whole graphic

    def setBottom(self, markers):
        #print markers
        self.bottomList = map (
            lambda (x,y): (x,y),
            markers) #legacy, can remove...
        self.bottom = YIntervalSeries("Candidate balancing selection")
        if len(markers) > 0:
            self.bottom.add(0.0, -1.0, -1.0, self.bottomList[0][1])
        for marker in self.bottomList:
            self.bottom.add(marker[0], -1.0, -1.0, marker[1])
            #if marker[0] > self.maxX: break
            #We do this at the end to fill the whole graphic


    def updateChartDataset(self, drawLabels=True):
        dataset = XYSeriesCollection()
        #self._calculateConfArea()
        #dataset.addSeries(self.confArea)
        dataset.addSeries(self.markers)
        plot = self.chart.getPlot()
        rangeAxis = plot.getRangeAxis()
        domainAxis = plot.getDomainAxis()
        rangeAxis.setRange(self.minY, self.maxY) #change
        domainAxis.setRange(0.0, self.maxX)
        #plot.setBackgroundPaint(Color.lightGray);
        #plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
        #plot.setDomainGridlinePaint(Color.white);
        #plot.setRangeGridlinePaint(Color.white);

        markerRenderer = XYLineAndShapeRenderer(False, True)
        #print self.markerColor
        markerRenderer.setSeriesPaint(0, self.markerColor)
        markerRenderer.setSeriesShape(0, Ellipse2D.Double(-3, -3, 6, 6))
        #markerRenderer.setToolTipGenerator(FDistToolTipGenerator(self.pointNames))
        plot.setRenderer(0, markerRenderer)
        plot.setDataset(0, dataset)
        dataset = XYSeriesCollection()
        if self.drawCI:
            dataset = YIntervalSeriesCollection()
            CIRenderer = DeviationRenderer(True, False)
            #CIRenderer.setOutline(True)
            #CIRenderer.setRoundXCoordinates(True)
            dataset.addSeries(self.bottom)
            dataset.addSeries(self.top)
            dataset.addSeries(self.limit)
            CIRenderer.setSeriesFillPaint(0, self.balColor)
            CIRenderer.setSeriesFillPaint(1, self.neuColor)
            CIRenderer.setSeriesFillPaint(2, self.posColor)
            CIRenderer.setSeriesPaint(0, self.balColor)
            CIRenderer.setSeriesPaint(1, self.neuColor)
            CIRenderer.setSeriesPaint(2, self.posColor)
            plot.setDataset(1, dataset)
            plot.setRenderer(1, CIRenderer)
        plot.setDataset(1, dataset)
        if drawLabels: self.drawLabels()

    def resetData(self, justAnnots = False):
        if not justAnnots:
            self.markers = XYSeries("Markers")
        self.drawCI = False
        self.chart.getPlot().clearAnnotations()
        if hasattr(self, 'pv'):
            del(self.pv)
        self.updateChartDataset()

    def save(self, parent, format):
        chooser = JFileChooser()
        #filter = FileNameExtensionFilter(
        #    format + " files",
        #    array([format, format.lower()], String))
        #chooser.setFileFilter(filter);
        returnVal = chooser.showSaveDialog(parent)
        if returnVal == JFileChooser.APPROVE_OPTION:
            fileName = chooser.getSelectedFile().getPath()
            if not fileName.upper().endswith('.' + format):
                fileName += '.' + format.lower()
            file = File(fileName)
        else:
            return
        if format == 'PNG':
            ChartUtilities.saveChartAsPNG(file, self.chart, self.exportX, self.exportY)
        elif format == 'SVG':
            domImpl = GenericDOMImplementation.getDOMImplementation()
            doc = domImpl.createDocument(None, "svg", None)
            svgGen = SVGGraphics2D(doc)
            svgGen.getGeneratorContext().setPrecision(6)
            self.chart.draw(svgGen,
               Rectangle2D.Double(0, 0, self.exportX, self.exportY), None)
            out = OutputStreamWriter(FileOutputStream(file), "UTF-8")
            svgGen.stream(out, True) #True is for useCSS
            out.close()
        elif format == 'PDF':
            mapper = DefaultFontMapper()
            pageSize = Rectangle(self.exportX, self.exportY)
            doc = TextDocument(pageSize, 50, 50, 50, 50)
            out = BufferedOutputStream(FileOutputStream(file))
            writer = PdfWriter.getInstance(doc, out)
            doc.open()
            cb = writer.getDirectContent()
            tp = cb.createTemplate(self.exportX, self.exportY)
            g2 = tp.createGraphics(self.exportX, self.exportY, mapper)
            r2D = Rectangle2D.Double(0, 0, self.exportX, self.exportY)
            self.chart.draw(g2, r2D)
            g2.dispose()
            cb.addTemplate(tp, 0, 0)
            doc.close()
            #out.close()

    def __init__(self, width, height):
        JPanel()
        self.minY = -0.05
        self.maxX = 1.0
        self.maxY = 1.0
        self.drawCI = False
        self.title = "Fst/He"
        self.labelSelected = True
        self.labelNeutral = False
        self.posColor = Color.RED
        self.neuColor = Color.LIGHT_GRAY
        self.balColor = Color.YELLOW
        self.markerColor = Color.BLUE
        self.exportX = width
        self.exportY = height
        self.chart = self._createEmptyChart()
        self.chart.setAntiAlias(False)
        self.resetData()
        self.cp = ChartPanel(self.chart)
        self.cp.setDisplayToolTips(True)
        self.cp.setPreferredSize(Dimension(width, height))
        self.add(self.cp)
コード例 #18
0
	def __init__(self,chart):
		chartPanel = ChartPanel(chart)
		chartPanel.setPreferredSize(Dimension(800,600))
		chartPanel.setMouseZoomable(True,False)
		self.setContentPane(chartPanel)