示例#1
0
def createHistogram(data):
    ''' Creates a histogram from a list of arbitrary numerical data in range from 0..1'''
    from org.jfree.data.category import DefaultCategoryDataset
    from org.jfree.chart import ChartFactory,ChartFrame
    from org.jfree.chart.plot import PlotOrientation
    from java.lang import Float
    
    numBins=20
    datamin = min(data)
    datamax = max(data)
    #binsize = 1.01 / numBins

    bins = {}
    for d in data:
        binkey = round(d,1)
        bin = bins.setdefault(binkey,0)
        bins[binkey] = bin + 1
        
    # Create dataset from bins
    dataset = DefaultCategoryDataset()

    # Ensure that bins exist even if they're empty
    i = datamin
    while i <= 1.0:
        bins.setdefault(round(float(i),1),0)
        i += .1
        
    #print "Number of bins:",len(bins)
    for bin in sorted(bins):
        #print "bin:",bin,type(bin)
        dataset.addValue(bins[bin],"","%05.2f"%(bin))
    
    # Create chart from dataset
    chart = ChartFactory.createBarChart(
                "", # chart title
                "Bin", # domain axis label
                "Number of occurrences", # range axis label
                dataset, # data
                PlotOrientation.VERTICAL, # orientation
                True, # include legend
                True, # tooltips?
                False # URLs?
                )
    plot = chart.getPlot()
    plot.getRenderer().setShadowVisible(False)
    frame = ChartFrame("Histogram", chart);
    frame.pack();
    frame.setVisible(True);
    return plot
示例#2
0
def category(data, name='', xlabel='', ylabel='', stacked=False, trid=False):
    """
  Creates a category bar chart.
    
  *data* is a ``dict`` whose keys are category names and whose values are 
  numerical (the height of the bar). 

  To plot multiple series *data* is specified as a ``dict`` whose keys are 
  series names and values are a ``dict`` of category names to numerical values.

  Setting *stacked* to ``True`` results in a stacked bar char. Setting *trid*
  to ``True`` results in a 3D bar chart.
  """
    dataset = DefaultCategoryDataset()
    for k, v in data.iteritems():
        if isinstance(v, dict):
            for k2, v2 in v.iteritems():
                dataset.addValue(v2, k2, k)
        else:
            dataset.addValue(v, "", k)

    if trid:
        if stacked:
            chart = ChartFactory.createStackedBarChart3D(
                name, xlabel, ylabel, dataset, PlotOrientation.VERTICAL, True,
                True, True)
        else:
            chart = ChartFactory.createBarChart3D(name, xlabel, ylabel,
                                                  dataset,
                                                  PlotOrientation.VERTICAL,
                                                  True, True, True)
    else:
        if stacked:
            chart = ChartFactory.createStackedBarChart(
                name, xlabel, ylabel, dataset, PlotOrientation.VERTICAL, True,
                True, True)
        else:
            chart = ChartFactory.createBarChart(name, xlabel, ylabel, dataset,
                                                PlotOrientation.VERTICAL, True,
                                                True, True)
    return Chart(chart)
示例#3
0
文件: bar.py 项目: bradh/geoscript-py
def category(data, name="", xlabel="", ylabel="", stacked=False, trid=False):
    """
  Creates a category bar chart.
    
  *data* is a ``dict`` whose keys are category names and whose values are 
  numerical (the height of the bar). 

  To plot multiple series *data* is specified as a ``dict`` whose keys are 
  series names and values are a ``dict`` of category names to numerical values.

  Setting *stacked* to ``True`` results in a stacked bar char. Setting *trid*
  to ``True`` results in a 3D bar chart.
  """
    dataset = DefaultCategoryDataset()
    for k, v in data.iteritems():
        if isinstance(v, dict):
            for k2, v2 in v.iteritems():
                dataset.addValue(v2, k2, k)
        else:
            dataset.addValue(v, "", k)

    if trid:
        if stacked:
            chart = ChartFactory.createStackedBarChart3D(
                name, xlabel, ylabel, dataset, PlotOrientation.VERTICAL, True, True, True
            )
        else:
            chart = ChartFactory.createBarChart3D(
                name, xlabel, ylabel, dataset, PlotOrientation.VERTICAL, True, True, True
            )
    else:
        if stacked:
            chart = ChartFactory.createStackedBarChart(
                name, xlabel, ylabel, dataset, PlotOrientation.VERTICAL, True, True, True
            )
        else:
            chart = ChartFactory.createBarChart(
                name, xlabel, ylabel, dataset, PlotOrientation.VERTICAL, True, True, True
            )
    return Chart(chart)
	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)
from org.apache.batik.dom import GenericDOMImplementation
from org.apache.batik.svggen import SVGGraphics2D


#Define the dataset
dataset = DefaultCategoryDataset()
dataset.addValue(25, 'S1', 'Slide XXX')#Value, serie name, X label
dataset.addValue(40, 'S1', 'Slide YYY')
dataset.addValue(60, 'S1', 'Slide ZZZ')

##############
# Plot Chart #
##############
#chart = ChartFactory.createLineChart(None,'Slide','% Brown Area',dataset,PlotOrientation.VERTICAL,False,True,False)
chart = ChartFactory.createBarChart("% Brown Area per Slide", 'Slide', '% Brown Area', dataset, PlotOrientation.VERTICAL, False,True,False)
# set the background color for the chart...
chart.setBackgroundPaint(Color.WHITE)

plot = chart.getPlot()
plot.setBackgroundPaint(Color.WHITE)
plot.setRangeGridlinesVisible(False)
plot.setAxisOffset(RectangleInsets.ZERO_INSETS)

#customise the range axis...
rangeAxis = plot.getRangeAxis()
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits())
rangeAxis.setAutoRangeIncludesZero(True)
#Set the Min Max value of the y axis
rangeAxis.setRange(0, 100)
#Create a custom BarRenderer
示例#6
0
def histogram(*data,**kwargs):
    ''' Creates a histogram. Takes the output from getData (a list of Facts), or alternately the
        same parameters that getData() takes. Takes an optional 'numBins=k' argument, where k
        specifies the number of bins. Returns the plot object in case you want to customize the 
        graph in some way. Takes an optional 'title' argument.
    '''
    # TODO: offset labels.
    from org.jfree.data.category import DefaultCategoryDataset
    from org.jfree.chart import ChartFactory,ChartFrame
    from org.jfree.chart.plot import PlotOrientation
    from java.lang import Float
    
    # Were we passed a dataset or parameters for obtaining a dataset?
    if len(data) == 3:
        station,date,element = data
        histogram(getData(station,date,element),**kwargs)
        return
    else:
        data = data[0] # unwrap from tuple
    
    # Find min and max; decide on number of bins
    numBins=kwargs.get('numBins',16)
    datamin,datamax = _getminmax(data)
    binsize = abs((datamax - datamin) / (Decimal(numBins)*Decimal("0.999"))) # divide by .999; otherwise there's always a final bin with one member, the max
    if binsize == 0: 
        raise Exception("Cannot create histogram; all values are equal to "+str(datamin))
    
    title = kwargs.get('title',"Histogram")
    
    # Create bins based on value.
    stations = {}
    for d in data:
        if d.value in missingValues: continue
        binkey = round(float(datamin + binsize * int((d.value - datamin) / binsize)),2)
        name = d.station.getNameString()+", "+d.element.name
        bin = stations.setdefault(name,{}).setdefault(binkey,0)
        stations[name][binkey] = bin + 1
    # Create dataset from bins
    dataset = DefaultCategoryDataset()
    for station in stations:
        
        # Ensure that bins exist even if they're empty
        i = datamin
        while i < datamax:
            stations[station].setdefault(round(float(i),2),0)
            i += binsize
            
        #print "Number of bins:",len(stations[station])
        for bin in sorted(stations[station]):
            #print "bin:",bin,type(bin)
            dataset.addValue(stations[station][bin],station,Float(bin))
    
    # Create chart from dataset
    chart = ChartFactory.createBarChart(
                "", # chart title
                "Bin", # domain axis label
                "Number of occurrences", # range axis label
                dataset, # data
                PlotOrientation.VERTICAL, # orientation
                True, # include legend
                True, # tooltips?
                False # URLs?
                )
    plot = chart.getPlot()
    plot.getRenderer().setShadowVisible(False)
    frame = ChartFrame(title, chart);
    frame.pack();
    frame.setVisible(True);
    return plot