def test_to_svg_file_name(self): chart1 = leather.Chart() chart1.add_dots(self.data1) chart2 = leather.Chart() chart2.add_dots(self.data2) grid = leather.Grid() grid.add_many([chart1, chart2, chart1]) grid.to_svg('.test.svg') self.assertTrue(os.path.exists(TEST_SVG))
def test_to_svg_file_handle(self): chart1 = leather.Chart() chart1.add_dots(self.data1) chart2 = leather.Chart() chart2.add_dots(self.data2) grid = leather.Grid() grid.add_many([chart1, chart2, chart1]) with open('.test.svg', 'w') as f: grid.to_svg(f) self.assertTrue(os.path.exists(TEST_SVG))
def test_to_svg_file_name(self): chart = leather.Chart() chart.add_dots(self.data1) chart.to_svg('.test.svg') self.assertTrue(os.path.exists(TEST_SVG))
def scatterplot(self, x=0, y=1, path=None, width=None, height=None): """ Render a scatterplot using :class:`leather.Chart`. :param x: The name or index of a column to plot as the x-axis. Defaults to the first column in the table. :param y: The name or index of a column to plot as the y-axis. Defaults to the second column in the table. :param path: If specified, the resulting SVG will be saved to this location. If :code:`None` and running in IPython, then the SVG will be rendered inline. Otherwise, the SVG data will be returned as a string. :param width: The width of the output SVG. :param height: The height of the output SVG. """ if type(x) is int: x_name = self.column_names[x] else: x_name = x if type(y) is int: y_name = self.column_names[y] else: y_name = y chart = leather.Chart() chart.add_x_axis(name=x_name) chart.add_y_axis(name=y_name) chart.add_dots(self, x=x, y=y) return chart.to_svg(path=path, width=width, height=height)
def test_add_many(self): chart1 = leather.Chart() chart1.add_dots(self.data1) chart2 = leather.Chart() chart2.add_dots(self.data2) grid = leather.Grid() grid.add_many([chart1, chart2, chart1]) svg = self.render_chart(grid) self.assertElementCount(svg, '.axis', 6) self.assertElementCount(svg, '.series', 3) self.assertElementCount(svg, '.dots', 3) self.assertElementCount(svg, 'circle', 13)
def createChart(chartData, fileName): startDate = convertStringToDate(chartData["start_at"]) endDate = convertStringToDate(chartData["end_at"]) baseCurrency = chartData["base"] chartTitle = 'Exchange rate for {0}'.format(baseCurrency) chart = leather.Chart(chartTitle) chart.add_x_axis(tick_formatter = lambda a, b, c : convertDateToString(a)) chart.add_x_scale(startDate, endDate) ratesData = chartData["rates"] datesList = list(ratesData.keys()) datesList.sort() lineDataset = [] tempDate = datesList[0] labelsList = list(ratesData[tempDate].keys()) labelsList.sort() numberOfLines = len(labelsList) for _ in range(numberOfLines): lineDataset.append([]) for i in range(numberOfLines): for date in datesList: tempLabel = labelsList[i] dayRate = ratesData[date][tempLabel] lineDataset[i].append(dayRate) datesList = [ convertStringToDate(dateString) for dateString in datesList ] for i in range(numberOfLines): lineData = tuple(zip(datesList, lineDataset[i])) chart.add_line(lineData, name = labelsList[i]) chart.to_svg(fileName)
def make(values, title=None, x_name: str = None, y_name: str = None) -> BytesIO: """Make chart image from values and return as stream""" if not isinstance(values, list): values = list(values) # sort by x values = sorted(values, key=operator.itemgetter(0)) bio = BytesIO() bio.name = 'chart.jpeg' chart = leather.Chart(title) chart.add_x_axis(name=x_name, tick_formatter=_tick_formatter) chart.add_y_axis(name=y_name, tick_formatter=_tick_formatter) chart.add_line(values) svg_data = chart.to_svg(width=1200, height=800) bio.write(cairosvg.svg2png(svg_data)) bio.seek(0) return bio
def svg_data_for_query(queryset, field, chart_name, timezone, exclude_today=False): data, total_count = series_data_for_model( queryset, field, timezone, exclude_today=exclude_today) data_prev_period, total_count_prev_period = series_data_for_model( queryset, field, timezone, prev_period=True, exclude_today=exclude_today) # Show every date on the x axis x_axis_ticks = [] for item in data: x_axis_ticks.append(item[0]) chart = leather.Chart() chart.add_x_axis(ticks=x_axis_ticks) # Start at 0 - Turn this into an option y_max = max([item[1] for item in data]) y_max_prev_period = max([item[1] for item in data_prev_period]) chart.add_y_scale(0, max([y_max, y_max_prev_period])) current_label, prev_period_label = series_labels(total_count, total_count_prev_period) chart.add_line(data, name=current_label, stroke_color=PRIMARY_STROKE_COLOR) chart.add_line(data_prev_period, name=prev_period_label, stroke_color=PREV_PERIOD_STROKE_COLOR, stroke_dasharray='5') chart.to_svg('/tmp/{}.svg'.format(chart_name), width=480, height=240) with open('/tmp/{}.svg'.format(chart_name)) as svgfile: svg_data = svgfile.read() svg2png(url='/tmp/{}.svg'.format(chart_name), write_to='/tmp/{}.png'.format(chart_name), scale=2) return svg_data
def column_chart(self, label=0, value=1, path=None, width=None, height=None): """ Render a column chart using :class:`leather.Chart`. :param label: The name or index of a column to plot as the labels of the chart. Defaults to the first column in the table. :param value: The name or index of a column to plot as the values of the chart. Defaults to the second column in the table. :param path: If specified, the resulting SVG will be saved to this location. If :code:`None` and running in IPython, then the SVG will be rendered inline. Otherwise, the SVG data will be returned as a string. :param width: The width of the output SVG. :param height: The height of the output SVG. """ if type(label) is int: label_name = self.column_names[label] else: label_name = label if type(value) is int: value_name = self.column_names[value] else: value_name = value chart = leather.Chart() chart.add_x_axis(name=label_name) chart.add_y_axis(name=value_name) chart.add_columns(self, x=label, y=value) return chart.to_svg(path=path, width=width, height=height)
def test_add_one(self): chart1 = leather.Chart() chart1.add_dots(self.data1) chart2 = leather.Chart() chart2.add_dots(self.data2) grid = leather.Grid() grid.add_one(chart1) grid.add_one(chart2) svg = self.render_chart(grid) self.assertElementCount(svg, '.axis', 4) self.assertElementCount(svg, '.series', 2) self.assertElementCount(svg, '.dots', 2) self.assertElementCount(svg, 'circle', 9)
def test_unicode(self): chart = leather.Chart() chart.add_bars([(1, u'👍')]) svg = self.render_chart(chart) self.assertElementCount(svg, '.axis', 2) self.assertElementCount(svg, '.series', 1)
def test_to_svg_file_handle(self): chart = leather.Chart() chart.add_dots(self.data1) with open('.test.svg', 'w') as f: chart.to_svg(f) self.assertTrue(os.path.exists(TEST_SVG))
def reset(): """ Setzt das momentane Diagramm zurück. :return: None """ global _chart, _count _chart = leather.Chart() _count = 0
def test_set_axes(self): chart = leather.Chart() chart.set_x_axis(leather.Axis(ticks=3)) chart.set_y_axis(leather.Axis(ticks=3)) chart.add_dots(self.data1) svg = self.render_chart(chart) self.assertTickLabels(svg, 'left', ['3', '6', '9']) self.assertTickLabels(svg, 'bottom', ['4', '8', '0'])
def test_add_scales(self): chart = leather.Chart() chart.add_x_scale(0, 20) chart.add_y_scale(0, 20) chart.add_dots(self.data1) svg = self.render_chart(chart) self.assertTickLabels(svg, 'left', ['5', '10', '15', '20', '0']) self.assertTickLabels(svg, 'bottom', ['5', '10', '15', '20', '0'])
def test_add_axes(self): chart = leather.Chart() chart.add_x_axis(ticks=[0, 4, 8]) chart.add_y_axis(ticks=[3, 6, 9]) chart.add_dots(self.data1) svg = self.render_chart(chart) self.assertTickLabels(svg, 'left', ['3', '6', '9']) self.assertTickLabels(svg, 'bottom', ['4', '8', '0'])
def test_single_series(self): chart = leather.Chart() chart.add_dots(self.data1) svg = self.render_chart(chart) self.assertElementCount(svg, '.axis', 2) self.assertElementCount(svg, '.series', 1) self.assertElementCount(svg, '.dots', 1) self.assertElementCount(svg, 'circle', 4)
def test_ticks(self): chart = leather.Chart() chart.add_dots(self.data) axis = leather.Axis(ticks=[-12, 0, 17, 44, 87, 99]) chart.set_x_axis(axis) svg = self.render_chart(chart) self.assertTickLabels(svg, 'bottom', ['-12', '17', '44', '87', '99', '0'])
def test_ticks(self): chart = leather.Chart() chart.add_dots(self.data) axis = leather.Axis(ticks=6) chart.set_x_axis(axis) svg = self.render_chart(chart) self.assertTickLabels(svg, 'bottom', ['2', '4', '6', '8', '10', '0'])
def test_scale_domain_warning(self): chart = leather.Chart() chart.add_x_scale(4, 7) chart.add_y_scale(0, 20) chart.add_dots(self.data1) with warnings.catch_warnings(): warnings.simplefilter('error') with self.assertRaises(UserWarning): self.render_chart(chart)
def report(request): """Generates all reports accessible to a user.""" if request.user.profile.admin_not_simulating(): # Admin sees reports for all checks checks = Check.objects.all() heading = 'Reports for All Checks' elif request.user.profile.supervisor_up(): # Supervisor sees reports for a company checks = Check.objects.filter(user__profile__company=request.user.profile.company) heading = 'Reports for Company: {}'.format(request.user.profile.company) else: # Regular user sees reports for his checks. checks = Check.objects.filter(user=request.user) heading = 'Reports for Your Checks' # Find out the start and end date end_date = datetime.datetime.now().date() start_date = end_date - datetime.timedelta(days=7) if request.method == 'POST': form = ReportForm(request.POST) if form.is_valid(): start_date = form.cleaned_data['start_date'] end_date = form.cleaned_data['end_date'] else: form = ReportForm() logger.info(start_date) # Generate the number of checks paid/not paid. copy = checks.filter(date_created__date__range=(start_date, end_date)) paid = len([c for c in copy if c.paid]) not_paid = len(copy) - paid data = [ (paid, 'Checks Paid'), (not_paid, 'Checks Not Paid') ] chart = leather.Chart('Checks Processed by CheckIt') chart.add_bars(data) chart.to_svg('checkit/static/img/bars.svg') # Generate the charts (django-chartit) paid_count_chart = generate_chart(checks, start_date, end_date, 'paid_date', 'count', Count('paid_date'), 'Checks Paid by Date', 'Paid Date') paid_total_chart = generate_chart(checks, start_date, end_date, 'paid_date', 'total', Sum('amount_paid'), 'Total Revenue by Date', 'Date') charts = [paid_count_chart, paid_total_chart] for i in range(3): group = 'letter{}_date'.format(i + 1) chart = generate_chart(checks, start_date, end_date, group, 'count', Count(group), 'Letter {} Generated by Date'.format(i + 1), 'Date') charts.append(chart) # Return all the charts to report view context = {'charts': charts, 'form': form, 'heading': heading} return render(request, 'report/report.html', context)
def make_chart(counter, name): """Make SVG charts and save them in /tmp. :param counter: A counter object with counts for every year/month. :param name: The name of the dataset to be used for the filename and the legend. :return: None, however, a file is created in /tmp named `name`.svg """ chart = leather.Chart(name) chart.add_bars(sorted(counter.items(), key=lambda t: t[0]), x=1, y=0) chart.to_svg('/tmp/%s.svg' % name.lower())
def make_time_graph(values, out_file, names=[]): import leather leather.theme.legend_font_family = 'Roboto' leather.theme.legend_font_size = '12' leather.theme.legend_color = '#999999' leather.theme.tick_font_family = 'Roboto' leather.theme.tick_font_size = '12' leather.theme.tick_color = '#aaa' colors = [ "#8c00e2", "#1981d4", "#00a22c", "#ea8500", "#e32d14", "#ff72db", "#00d69e", "#1618db", ] if len(names) != 0: if len(names) != len(values): print("You've given me " + str(len(values)) + "" " series but " + str(len(names)) + " names. Aborting.") return # Find the earliest and latest dates in all series. first_date_string = values[0][0][0] last_date_string = values[0][-1][0] for series in values: for point in series: if point[0] < first_date_string: first_date_string = point[0] if point[0] > last_date_string: last_date_string = point[0] first_date_parts = [int(v) for v in first_date_string.split("-")] last_date_parts = [int(v) for v in last_date_string.split("-")] first_date = datetime.combine(date(*first_date_parts), datetime.min.time()) last_date = datetime.combine(date(*last_date_parts), datetime.min.time()) chart = leather.Chart("") chart.add_x_scale(first_date, last_date) for i in range(len(values)): name = names[i] if len(names) > i else "" series = [] for point in values[i]: date_parts = [int(p) for p in point[0].split("-")] d = datetime.combine(date(*date_parts), datetime.min.time()) value = float(point[1]) series.append([d, value]) chart.add_line(series, name=name, width=0.75, stroke_color=colors[i % len(colors)]) chart.to_svg("temp.svg") os.system("convert -density 1000 temp.svg " + out_file) os.system("rm temp.svg")
def test_tick_formatter(self): chart = leather.Chart() chart.add_dots(self.data) def test_formatter(value, i, count): return '%i+' % (value * 10) axis = leather.Axis(tick_formatter=test_formatter) chart.set_x_axis(axis) svg = self.render_chart(chart) self.assertTickLabels(svg, 'bottom', ['25+', '50+', '75+', '100+', '0+'])
def costChart(a, b): data = [('Wind', float(a)), ('Solar', float(b))] os.remove( "/Users/jakechoward/Desktop/GreenSwitch/Nasa-Hackathon-2019-master/costSetup.svg" ) chart = leather.Chart( 'Cost to implement 50% daily generation in your area') chart.add_columns(data, fill_color='#8CC63F') chart.to_svg('costSetup.svg') return chart
def generate_chart(self): import webbrowser from colors import palette48_iwanthue as palette if self.server_temp_counts[0]['filename'] == '': txt = 'Nothing to plot' self.status_lbl.label.configure(text=txt) return None if len(self.server_temp_counts) > len(palette): txt = 'Plotting only avaialble for max %d files'.format( len(palette)) self.status_lbl.label.configure(text=txt) return None filepath = os.path.join(self.path, 'results_chart.svg') max_temp = float(self.temp_spiner.get()) colors = [ 'rgb(%i, %i, %i)' % (color[0], color[1], color[2]) for color in palette ] leather.theme.default_series_colors = colors name = self.path.split('/')[-1] name = self.path.split('\\')[-1] chart = leather.Chart('Results for: ' + name) chart.add_x_scale(15, 40) chart.add_x_axis(ticks=[i for i in range(15, 40)]) ymax = 0 details = copy.deepcopy(self.server_temp_counts) for file, color in zip(details, palette): name = file['filename'][:-4] del file['filename'] data = [] for x, y in file.items(): data.append((float(x), y)) ymax = max(ymax, y) #color = 'rgb(%i, %i, %i)' % (color[0],color[1],color[2]) chart.add_line(data, name=name, width=1) name = '%ddegC limit' % max_temp chart.add_line([(max_temp, 0), (max_temp, ymax)], name=name, width=.5, stroke_color='rgb(105,105,105)') chart.to_svg(filepath) url = "file://%s" % filepath webbrowser.open(url, new=2)
def main(input_csv): data_csv = input_csv with open(data_csv) as f: ur = UnicodeReader(f) next(ur) data = list(ur)[:] row_size = len(data[0][:]) - 1 for row in data: for index in range(row_size): row[index + 1] = float(row[index + 1]) if row[index + 1] is not None else None for value in range(3): data_sorted = sorted(data, key=lambda x: x[value + 1], reverse=True) chart = leather.Chart('Chart - CSV') chart.add_bars(data_sorted[:30], x=(value + 1), y=0) chart_output = 'generated/charts_leather_{0}.svg'.format(value) chart.to_svg(chart_output) print('[i] following chard was generated: "{0}"'.format(chart_output))
def validityChart(a, b): data = [('Wind', float(a)), ('Solar', float(b))] os.remove( "/Users/jakechoward/Desktop/GreenSwitch/Nasa-Hackathon-2019-master/validSetup2.svg" ) chart = leather.Chart('Validity Ranking') chart.add_columns(data, fill_color='#8CD63F') chart.to_svg('validSetup2.svg') return chart #def createChart() #data = [ # ('Hello', 3), # ('How', 5), # ('Are', 9), # ('You', 4) #] #chart = leather.Chart('Columns') #chart.add_columns(data) #chart.to_svg('examples/charts/columns.svg')
import leather data = [(0, 3), (4, 5), (7, 9), (8, 4)] chart = leather.Chart('Lines') chart.add_lines(data) chart.to_svg('examples/charts/lines.svg')
from datetime import date import leather data = [ (date(2015, 1, 1), 3), (date(2015, 3, 1), 5), (date(2015, 6, 1), 9), (date(2015, 9, 1), 4) ] chart = leather.Chart('Temporal') chart.add_x_scale(date(2014, 1, 1), date(2016, 1, 1)) chart.add_line(data) chart.to_svg('examples/charts/temporal.svg')