Package: newsworthycharts
This  module contains methods for producing graphs and publishing them on Amazon S3, or in the location of your choice.It is written and maintained forNewsworthy, but could possibly come in handy for other people as well.ByJournalism++ Stockholm.InstallingpipinstallnewsworthychartsUsingThis module comes with two classes,ChartandStorage(and it’s subclasses).
When using the Chart class, the generated chart will be saved as a local file:fromnewsworthychartsimportSerialChartasChartc=Chart(600,800)c.title="Number of smiles per second"c.xlabel="Time"c.ylabel="Smiles"c.caption="Source: Ministry of smiles."data_serie_1=[("2008-01-01",6.1),("2009-01-01",5.9),("2010-01-01",6.8)]c.data.append(data_serie_1)c.highlight="2010-01-01"c.render("test","png")You can use one of the predefine chart classes to make common chart types. Or you can use Newsworthycharts together with Matplotlib. This is useful is you just want to add text elements such as subtitle, notes or apply a predefine theme.Here is how you would make a pie chart:# datalabels='Frogs','Hogs','Dogs','Logs'sizes=[15,30,45,10]# setup chartchart=Chart(width=800,height=600,storage=local_storage)chart.title="My pie chart"chart.subtitle="Look at all those colors"# NB: Render the chart to `chart.ax`chart.ax.pie(sizes,labels=labels,autopct='%1.1f%%')# Save the chartchart.render("tailored_chart","png")You can use a _storage_ object to save file to
a specific location or cloud service:fromnewsworthychartsimportChartfromnewsworthychartsimportS3Storages3=S3Storage("my_bucket")c=Chart(600,800,storage=s3)c.title="Number of smiles per second"c.subtitle="This chart tells you something very important."c.xlabel="Time"c.ylabel="Smiles"c.note="There are some missing smiles in data"c.caption="Source: Ministry of smiles."c.render("test","png")To store a file in a local folder, use theLocalStorageclass:fromnewsworthychartsimportLocalStoragestorage=LocalStorage("/path/to/generated/charts")Charts are styled using built-in or user-defined styles:fromnewsworthychartsimportChart# This chart has the newsworthy default stylec=Chart(600,800,style="newsworthy")# Style can also be the path to a style file (absolute or relative to current working directory)c2=Chart(600,800,style="path/to/styles/mystyle.mplstyle")To set up you own style, copy the build-in default: <https://github.com/jplusplus/newsworthycharts/blob/master/newsworthycharts/rc/newsworthy>Newsworthycharts will look first among the predefined style files for the requested style, so if you have a custom style file in you working directory you need to give it a unique name not already in use.OptionsChartdata: A list of datasetsannotate_trend = True  # Print out values at points on trendline?trendline = []  # List of x positions, or data pointslabels = []  # Optionally one label for each datasetannotations = []  # Manually added annotationsinterval = None  # yearly|quarterly|monthly|weekly|dailyunits = ‘number’  # number|percent|degreesshow_ticks = True  # toggle category names, dates, etcsubtitle = Nonenote = Nonexlabel = Noneylabel = Nonecaption = Nonehighlight = A position (typically a date, category label or index) to highlight. The semantics may differ somewhat between chart types.decimals = None  # None means automatically chose the best numberlogo = None  # Path to image that will be embedded in the caption area. Can also be set though a style propertycolor_fn = None  # Custom coloring functionDevelopingTo run tests:python3-mflake8python3-mpytestDeploymentTo deploy a new version to [PyPi](https://pypi.org/project/newsworthycharts):Update Changelog below.Update the version number in newsworthycharts/__init__.pyCreate and push a git tag:git tag VERSION; git push –tags(not strictly needed, but nice)Build:python3 setup.py sdist bdist_wheelCheck:python3 -m twine check dist/newsworthycharts-X.Y.X*Upload:python3 -m twine upload dist/newsworthycharts-X.Y.X*…assuming you have Twine installed (pip3 install twine) and configured.RoadmapAdding more base mapsGetting rid of custom settings-hackCustom month locator with equal-width month barsChangelog1.54.5Improved tick placement in daily chartsMinor upgrades: matplotlib==3.8.3; Pillow==10.2.0; geopandas==0.14.31.54.4Use Babel 2.14, and pin versionRequire numpy>=1.21.0 (now required by Matplotlib)Patch upgrades: matplotlib==3.8.2; geopandas==0.14.11.54.3Fix duplicated integer values in y axis1.54.2Make sure that legend is always on top of bars in stacked bar chartsSupport more stacked categories in serial bar charts1.52.2+Backport various 1.54.x fixes1.54.1Patch upgrade Matplotlib to 3.8.11.54.0Treat ‘jpeg’ format as ‘jpg’Fixed a rendering bug in stacked bar charts with multiple values being 0Pillow upgraded to 10.11.53.0Fixed bug in value_labels, trying to access a color value that didn’t existDropped Python 3.8 support (upstream)Uses Matplotlib 3.8Uses Pillow 101.52.1Fixed date formatting issue in daily charts1.52.0No longer render EPS files by default.1.51.2_Really_ fix dependencies1.51.1Fix error in dependency verison1.51.0AddedBubbleMapAddedse-4basemap for Swedish countiesBasemaps can now have multiplygonsDowngraded adjustText to 0.7.3, as upgrade broke rendering constistency in some places1.50.2Revertmatplotlib-label-linesto previous version.1.50.0Dropped Python 3.7 support (upstream)Pinned Pillow to exact version in setup.py, for consistent renderingStripeChart: First draft1.49.1ProgressChart: Better value label placement.1.49.0ProgressChart: Enable custom value labels as third argument in data serie.1.48.2Bug fix: Handle translation in inset maps inChoroplethMap.1.48.1Bug fix: Path to translation file inChoroplethMap.1.48.0ChoroplethMap: Allow Newsworthy region names.RangePlot: Re-addstart_labelthat had been (mistakenly?) commented out.1.47.2Bug fix: Fixes legend issue inProgressChart.1.47.1Data point annotation now works for serial charts as wellBug fix: Re-enablequalitative_colorsascolorargument in SerialChart (line).1.47.0Support for rendering jpeg files, asjpgMinimum required Python version is now 3.7 (jumping from 3.5)Matplotlib@3.7.11.46.3Fix z-ordering issue on multiple series (n > 2)1.46.2Fix tag mismatch in dist1.46.1Add missing haversine transform for non-projected crs1.46.0heightcan be set to None for automatic ratio, for chart types that support it. Will default to 1:1 for most chart types, but maps will try to provide a reasonable default based on geometry. Some chart types still require explicit heightIt is now possible to use subsets of basemaps, by specifying a prefix:se|03-7means regions starting with03inse-7Added .missing_label to ChoroplethMap. If None (default), no label will be printed.Always accentuate base_line (/y=0), and make sure that line is on top of any bars to avoid “floating” barsImproved error handling in ChoroplethMapClean up figure layout logic (this should speed up rendering somewhat)1.45.0Increased defaultmax_ticksin SerialChart to 7Matplotlib==3.7.0adjustText==0.8.0ChoroplethMap legend formatting, following language, decimals and units settings, etcMinor tweaks to the layout algorithm. Might affect padding in some charts.ChoroplethMap now does some basic normalizing of region codesAdded some data sanity checks, and improved error messages in ChoroplethMapAdded tests for ChoroplethMap1.44.4Do not default to broken y axis if chart contains a bar series.1.44.3Fix bug and occasional crash when using baseline with None values1.44.2Fix crash in serialchart coloring chain1.44.1Fix regression in SeasonalChart bar coloring1.44.0Added grey outline to choropleth mapsThetypeargument is now a list with one type per data serie. Using a string is still supported for backwards compability. This makes it possible to make mixed type charts.Reworked, simpler and more stable bar coloring algorithmThetypeargument is no longer a getter/setterReduced edge for bar chartswith many barsRemoved unused, undocumented special colors value“qualitative_colors”. We have reasonable defaults for all chart types, that can already be overridden. The qualitative colors are used by default for qualitative data.Removed unused, undocumented support for highlighting a series by label, rather than a value. The first series is highlighted by default, and that behaviour can already be overriden by the.colorssetting1.43.4Add more space for label title on se-7 maps1.43.3Don’t try to render map insets with no dataUse style colors in categorical choropleth mapsAdded missing support for coloring categorical maps with.colorsMake automatic labeling work on categorical maps with.colorsSomewhat lighter fill for missing values in choropleth maps (lightgray -> gainsboro)Testing experimental label_title support, to be documented in 1.44.01.43.2Fixed weird ymax in some baseline casesAdded bottom padding when baseline was below data-min1.43.1Fixed cut off-bug with negative baselineFix coloring bug in warm_cold color_fn with baselineFix regression with quarterly locator1.43.0Default to weekdays on x-axis if data spans 7 days or lessAdded.color_labelsto label bar colors set by.color_fn1.42.0Added.baselinesetting for bar chartswarm_coldcoloring algorithm now works relative.baselineAdded.baseline_annotation.color_fncan now be a lambda function (or the name of one of the built in functions), e.g.chart.color_fn = lambda x: “red” if x < 1.4 else “green”Bar charts will now always have a small white edgeDon’t break y axis if data is close to 0Offset quarters will be recognosed as quarters now (e.g. Feb, May, Aug, Nov)Fixed bug in .allow_broken_y_axis implementation, causing y-axis to be broken in too many placesVarious dependency updatesReplaced deprecated PIL.Image.ANTIALIAS with PIL.Image.Resampling.LANCZOS for logotype resizing.Get rid of warnings about missing “glyph 10” when prerendering text to calculate text bos sizesFixed bug where single values surrounded my None’s were not printed out in serial-data line charts. This was an earlier regression that was not noticed for many releases.1.41.0New, experimental chart type: Choropleth maps! Supports both categorical and continuous data.Better support for monthly time series spanning yearsFixed bug where missing annotation slots could crash CategoricalChart1.40.2Don’t crash on deprecation warningMatplotlib upgraded from 3.6.2 to 3.6.3Pin some critical requirement versions1.40.1Fix floating point bug in percent labelsTest fixes1.40.0Auto-decide.decimalsif NoneRound 0.5 to 1, etc in value axis labels and annotations (theROUND_HALF_UPbehaviour)Add.force_decimalsto print out e.g. ”1.0”. Requires.decimalsto be explicitly setSerial Chart: Allow disabling ”broken y axis” feature by settingallow_broken_y_axis=FalseDeprecatedunits=”count”. Make all numbers equal. Useunits=”number”anddecimals=0to get the earlier behaviour.Remove overriding of decimal settings by units = countRemove noisy deprecation warning on user settings in rc filesFormatters will now use the correct minus signs for the given locale.1.39.1Added missing metadata to svgAdded .__version__ attribute to the package1.39.0Added pdf export, now more widely used than epsAuthor and software metadata now added to pdf and png, including the exakt NWCharts version used to produce an image1.38.2S3Storage: Handle text files.1.38.1Prevent logo from ever being > 155px, to restore previous behaviour.1.38.0Made multi series bar seasonal bar charts work for opposite signs, so that we can make +/- charts1.37.3Bug fix: Don’t crash with factor argument in DW charts.1.37.2Fixed rendering bug in non-transparent eps exports with transparent logos1.37.1Fixed bug in argument parsing in S3Storage.save()1.37.0Addedstorage_optionsargument torender()andrender_all()Unified function signatures across storage classes.1.36.0Added options argument toS3Storage.save()1.35.0Enable logo scaling. Provided logos can now be any size, and will be scaled down to an appopriate format.1.34.0Addsfactorargument to.render()and.render_all().Adds missingtransparentargument to.render_all().Matplotlib @ 3.6.2langcodes @ 3.3 to ensure consistent handling of macro languages (nois a valid language)1.33.0:Addstransparentargument to render method.1.32.3ScatterPlot: Mark labeled dots more clearly.1.32.2SerialChart: Better error when timepoints are duplicated.1.32.1Bug fixes: Handle negative values whenymin=0in SerialChart and remove line stroke fromhighlighted_x_ranges.1.32.0SerialChart: New options:line_widthandhighlighted_x_ranges.1.31.0Addedlabel_placement=’outside’option to SerialChart1.30.0Matplotlib updated from 3.3 to 3.6, including among many, many other things:
- support for .webp
- a lot of additions and improvements to rcParams
- new backendsCustom NWCharts parameters to the rc style file is being deprecated, and should eventually be phased outMatplotlib and related modules are now pinned to a specific versionAdded support for generating webp images!Upgraded pytest to support Python 3.10+Fixed date locators to use thecorrect langauge/localeAdded padding on top of title, to avoid cropping diactritics1.29.0CategoricalChart: Make it possible to hide legend.1.28.1CategoricalChartWithReference: Handle multi color bars.1.28.0Chart/SerialChart: New feature: Mark broken y axis with symbol.1.27.1SerialChart: Force y axis range to to given values whenymaxandyminis defined.1.27.0SerialChart: Enable value labeling of each point on line.1.26.1Highlight only current value in SeasonalChart; use different shades of grey for the rest1.26.0AddSeasonalChart, a.k.a the Olsson chart1.25.3ProgressChart: Handle missing valueslib.formatter.Formatter: Handle null values1.25.2ScatterPlot: Enable ymin and xmin in scatterplot.1.25.1Color annoation outline by background color.1.25.0Improved ScatterPlot.1.24.1Bug fix: Inline labeling on charts with missing data.1.24.0CategoricalChartWithReference: Adds highlight option1.23.1Adds missing dependency.1.23.0SerialChart: Introduces inline labeling on lines1.22.1Tweeks on line labeling1.22.0SerialChart: Introduces labeling on lines (rather than just legends)1.21.5Bug fix: Handle charts without ticks to be able to render pie charts again1.21.4Beter height handling in header and footer.Make Noto Sans default font.1.21.3Enable colors property in stacked bar SerialChart.1.21.2Adjusts x margin in RangePlot to fit value labels better.Increases line spacing in subtitle.1.21.1Bug fix: Small change in Datawrapper API.Make ticks option work with SerialChart.init_from1.21.0New feature: Use baseChartclass to make custom charts.Bug fix: Labels outside canvas in RangePlot1.20.2ClimateCars: Tweeks on 2030 chart.1.20.1Handle np.int as years.1.20.0CategoricalChart: Highlight multiple values with listBug fix: ylabel placed outside canvasStyle: Align caption with note1.19.2RangePlot: Better label margins and bold labels.1.19.1RangePlot: Rename argument values_labels => value_labels.1.19.0Pick up qualitative colors from style file.1.18.1Fixed coloring on highlighted progress charts.Adds ability to highlight both ends on range plot.1.18.0Addedticksoption to SerialChart, to set custom x-axis ticksAdded color option to CategoricalChart, to work exactly as in SerialChartFixed bug with highlight in line charts where some line was outside the highlighted date.1.17.0Enable multiple targets in progress chart.1.16.2Fixes highlight bug in progress chart.1.16.1Small changes in range plot.1.16.0Adds CO2 budget chart1.15.2ClimateCar chart tweeks.1.15.1Bug fix: Adds newsworthycharts.custom to build.1.15.0Introduces progress charts and removes hard coded font sizes.1.14.0Introduces range plots and enables custom coloring in serial charts.1.13.3Fit long ticks on y axis.1.13.2Set annotation fontsize to same as ticks by default.1.13.1Bug fix: Subtitle placement1.13.0Introduces subtitle and note.Updates default styles to align with Newsworthy style guide.1.12.1Fit footer by logo height. Fixes bug that caused axis overlag when logo was large.1.12.0Introduces stacked categorical bar charts1.11.2Bug fix: Remove failing attemt to store chart in dw format1.11.1Corrects zorder and centers tick on CategoricalChartWithReference1.11.0Introduces new chart: CategoricalChartWithReference1.10.1Fixes bad X ticks in weekly SerialChart (and charts that don’t start in January).1.10.0Add annotation_rotation option to categorical chartsFix a crash in some special cases with serial charts shorter than a year.Fix a bug where diff between series was not highlighted if one value was close to zero.1.9.2Include translations in build.1.9.1Translates region to Datawrapper standard when making maps.1.9.0Allows list of dicts to be passed to DatawrapperChart to be make tables, categorical maps etc.1.8.2Require requests.1.8.1Bug fixes.1.8.0Introduces Datawrapper Chart type.1.7.0Adds ymax argument (to SerialChart)Bug fix: Handle missing values in SerialChart with line.1.6.12Bug fix: Set y max to stacked max in stacked bar chart.1.6.11Introduces stacked bars to SerialChart.1.6.10Fixes bar_orientation bug withinit_from()1.6.9Fix an ugly bug where type=line would not work withinit_from()1.6.8Some cosmetic changes: no legend if only one series, color updates, thinner zero line.1.6.7Make title and units work withinit_fromagain1.6.6Add warm/cold color function1.6.5Really, really makeinit_fromwork, by allowingly allowing allowed attributes1.6.4Fix bug whereinit_fromwould sometime duplicate data.Make sureinit_fromdoes not overwrite class methods.1.6.3Protect private properties from being overwritten byinit_fromWhenunitsis count,decimalshould default to 0 if not provided. This sometimes didn’t work. Now it does.1.6.2Makeinit_fromwork as expected with a language argument1.6.1Makeinit_fromwork as expected with multiple data series1.6.0Added a factory method to create charts from a JSON-like Python object, like so:SerialChart.init_from(config, storage)1.5.1Fix packaging error in 1.5.01.5.0Expose available chart engines inCHART_ENGINESconstant for dynamic loadingAddcolor_fnproperty, for coloring bars based on valueIncrease line width in default styleUpgrading Numpy could potentially affect how infinity is treated in serial charts.1.4.1Revert text adjusting for categorical charts, as it had issues1.4.0Add new ScatterPlot chart classImproved text adjusting in serial chartsMore secure YAML file parsing1.3.3Make small bar charts with very many bars look better1.3.2Make labels work again, 1.3.1 broke those in some circumstances1.3.1Make inner_max/min_x work with leading / trailing None valuesMake sure single, orphaned values are visible (as points) in line charts1.3.0Allow (and recommend) using Matplotlib 3. This may affect how some charts are rendered.Removed undocumented and incomplete Latex support from caption.Don’t highlight diff outside either series’ extreme ends.1.2.1Use strong color if there is nothing to highlight.1.2.0Fix a bug wheredecimalssetting was not used in all annotations. Potentially breaking in some implementations.Make the annotation offset 80% of the fontsize (used to be a hardcoded number of pixels)1.1.5Small cosmetic update: Decrease offset of annotation.1.1.4Require Matplotlib < 3, because we are still relying on some features that are deprecated there. Also, internal changes to Matplot lib may cause some charts to look different depending on version.1.1.3Make annotation use default font size, as relative sizing didn’t work here anyway1.1.2Move class properties to method properties to make sure multiple Chart instances work as intended/documented. This will make tests run again.None values in bar charts are not annotated (trying to annotate None values used to result in a crash)More tests1.1.1Annotations should now work as expected on series with missing data1.1.0Fix bug where decimal setting wasn’t always respectedMake no decimals the default if unit is “count”1.0.0First version