Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding a new viz line-bar chart #5144

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
50 changes: 50 additions & 0 deletions superset/assets/src/explore/visTypes.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -392,6 +392,56 @@ export const visTypes = {
},
},

line_bar: {
label: t('Line Bar Chart'),
requiresTime: true,
controlPanelSections: [
{
label: t('Chart Options'),
expanded: true,
controlSetRows: [
['color_scheme'],
['x_axis_format'],
],
},
{
label: t('Y Axis 1 (Bar)'),
expanded: true,
controlSetRows: [
['metric', 'y_axis_format'],
],
},
{
label: t('Y Axis 2 (Line)'),
expanded: true,
controlSetRows: [
['metric_2', 'y_axis_2_format'],
],
},
sections.annotations,
],
controlOverrides: {
metric: {
label: t('Left(Bar) Axis Metric'),
description: t('Choose a metric for left(Bar) axis'),
},
y_axis_format: {
label: t('Left(Bar) Axis Format'),
},
metric_2: {
label: t('Right(Line) Axis Metric'),
description: t('Choose a metric for right(Line) axis'),
},
y_axis_2_format: {
label: t('Right(Line) Axis Format'),
},
x_axis_format: {
choices: D3_TIME_FORMAT_OPTIONS,
default: 'smart_date',
},
},
},

bar: {
label: t('Time Series - Bar Chart'),
showOnExplore: true,
Expand Down
2 changes: 2 additions & 0 deletions superset/assets/src/visualizations/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ export const VIZ_TYPES = {
word_cloud: 'word_cloud',
world_map: 'world_map',
dual_line: 'dual_line',
line_bar: 'line_bar',
event_flow: 'event_flow',
paired_ttest: 'paired_ttest',
partition: 'partition',
Expand Down Expand Up @@ -110,6 +111,7 @@ const vizMap = {
[VIZ_TYPES.world_map]: () =>
loadVis(import(/* webpackChunkName: "world_map" */ './world_map.js')),
[VIZ_TYPES.dual_line]: loadNvd3,
[VIZ_TYPES.line_bar]: loadNvd3,
[VIZ_TYPES.event_flow]: () =>
loadVis(import(/* webpackChunkName: "EventFlow" */ './EventFlow.jsx')),
[VIZ_TYPES.paired_ttest]: () =>
Expand Down
14 changes: 10 additions & 4 deletions superset/assets/src/visualizations/nvd3_vis.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ const BREAKPOINTS = {
const TIMESERIES_VIZ_TYPES = [
'line',
'dual_line',
'line_bar',
'line_multi',
'area',
'compare',
Expand Down Expand Up @@ -224,6 +225,11 @@ export default function nvd3Vis(slice, payload) {
chart.interpolate('linear');
break;

case 'line_bar':
chart = nv.models.multiChart();
chart.interpolate('linear');
break;

case 'line_multi':
chart = nv.models.multiChart();
chart.interpolate(fd.line_interpolation);
Expand Down Expand Up @@ -489,15 +495,15 @@ export default function nvd3Vis(slice, payload) {
}
}

if (['dual_line', 'line_multi'].indexOf(vizType) >= 0) {
if (['dual_line', 'line_multi', 'line_bar'].indexOf(vizType) >= 0) {
const yAxisFormatter1 = d3.format(fd.y_axis_format);
const yAxisFormatter2 = d3.format(fd.y_axis_2_format);
chart.yAxis1.tickFormat(yAxisFormatter1);
chart.yAxis2.tickFormat(yAxisFormatter2);
const yAxisFormatters = data.map(datum => (
datum.yAxis === 1 ? yAxisFormatter1 : yAxisFormatter2));
customizeToolTip(chart, xAxisFormatter, yAxisFormatters);
if (vizType === 'dual_line') {
if (vizType === 'dual_line' || vizType === 'line_bar') {
chart.showLegend(width > BREAKPOINTS.small);
} else {
chart.showLegend(fd.show_legend);
Expand All @@ -516,7 +522,7 @@ export default function nvd3Vis(slice, payload) {
.call(chart);

// align yAxis1 and yAxis2 ticks
if (['dual_line', 'line_multi'].indexOf(vizType) >= 0) {
if (['dual_line', 'line_multi', 'line_bar'].indexOf(vizType) >= 0) {
const count = chart.yAxis1.ticks();
const ticks1 = chart.yAxis1.scale().domain(chart.yAxis1.domain()).nice(count).ticks(count);
const ticks2 = chart.yAxis2.scale().domain(chart.yAxis2.domain()).nice(count).ticks(count);
Expand Down Expand Up @@ -577,7 +583,7 @@ export default function nvd3Vis(slice, payload) {
margins.bottom = 40;
}

if (['dual_line', 'line_multi'].indexOf(vizType) >= 0) {
if (['dual_line', 'line_multi', 'line_bar'].indexOf(vizType) >= 0) {
const maxYAxis2LabelWidth = getMaxLabelSize(slice.container, 'nv-y2');
margins.right = maxYAxis2LabelWidth + marginPad;
}
Expand Down
74 changes: 74 additions & 0 deletions superset/viz.py
Original file line number Diff line number Diff line change
Expand Up @@ -2623,6 +2623,80 @@ def get_data(self, df):
return self.nest_values(levels)


class LineBarViz(NVD3Viz):

"""A simple line bar chart with dual axis"""

viz_type = 'line_bar'
verbose_name = _('Time Series - Line Bar Chart')
sort_series = False
is_timeseries = True

def query_obj(self):
d = super(LineBarViz, self).query_obj()
m1 = self.form_data.get('metric')
m2 = self.form_data.get('metric_2')
d['metrics'] = [m1, m2]
if not m1:
raise Exception(_('Pick a metric for left(bar) axis!'))
if not m2:
raise Exception(_('Pick a metric for right(line) axis!'))
if m1 == m2:
raise Exception(_('Please choose different metrics'
' on left and right axis'))
return d

def to_series(self, df, classed=''):
cols = []
for col in df.columns:
if col == '':
cols.append('N/A')
elif col is None:
cols.append('NULL')
else:
cols.append(col)
df.columns = cols
series = df.to_dict('series')
chart_data = []
metrics = [
self.form_data.get('metric'),
self.form_data.get('metric_2'),
]
for i, m in enumerate(metrics):
ys = series[m]

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this line execution returns a error: can not hash a dict

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

class LineBarViz(DistributionPieViz):
    """A rich line chart with dual axis"""
    viz_type = 'line_bar'
    verbose_name = _('Time Series - Line Bar Chart')
    sort_series = False
    is_timeseries = True
    def query_obj(self):
        d = super(LineBarViz, self).query_obj()
        m1 = self.form_data.get('metric')
        m2 = self.form_data.get('metric_2i')
        d['metrics'] = [m1, m2]
        if not m1:
            raise Exception(_('Pick a metric for left(bar) axis!'))
        if not m2:
            raise Exception(_('Pick a metric for right(line) axis!'))
        if m1['label'] == m2['label']:
            raise Exception(_('Please choose different metrics'
                            ' on left and right axis'))
        return d
    def to_series(self, df, classed=''):
        cols = []
        for col in df.columns:
            if col == '':
                cols.append('N/A')
            elif col is None:
                cols.append('NULL')
            else:
                cols.append(col)
        df.columns = cols
        series = df.to_dict('series')
        chart_data = []
        metrics = [
            self.form_data.get('metric')['label'],
            self.form_data.get('metric_2i')['label'],
        ]
        for i, m in enumerate(metrics):
            ys = series[m]
            if df[m].dtype.kind not in 'biufc':
                continue
            series_title = m
            d = {
                'key': series_title,
                'classed': classed,
                'values': [
                    {'x': ds, 'y': ys[ds] if ds in ys else None}
                    for ds in df.index
                ],
                'yAxis': i + 1,
                'type': 'bar' if i==0 else 'line',
            }
            chart_data.append(d)
        return chart_data
    def get_data(self, df):
        fd = self.form_data
        df = df.fillna(0)
        if self.form_data.get('granularity') == 'all':
            raise Exception(_('Pick a time granularity for your time series'))
        metric = fd.get('metric')
        metric_2i = fd.get('metric_2i')
        print(metric)
        df = df.pivot_table(
            index=DTTM_ALIAS,
            values=[metric['label'], metric_2i['label']])
        chart_data = self.to_series(df)
        return chart_data

This May help you

if df[m].dtype.kind not in 'biufc':
continue
series_title = m
d = {
'key': series_title,
'classed': classed,
'values': [
{'x': ds, 'y': ys[ds] if ds in ys else None}
for ds in df.index
],
'yAxis': i + 1,
'type': 'bar' if i == 0 else 'line',
}
chart_data.append(d)
return chart_data

def get_data(self, df):
fd = self.form_data
df = df.fillna(0)

if self.form_data.get('granularity') == 'all':
raise Exception(_('Pick a time granularity for your time series'))

metric = self.get_metric_label(fd.get('metric'))
metric_2 = self.get_metric_label(fd.get('metric_2'))
df = df.pivot_table(
index=DTTM_ALIAS,
values=[metric, metric_2])

chart_data = self.to_series(df)
return chart_data


viz_types = {
o.viz_type: o for o in globals().values()
if (
Expand Down