使用nvd3从dataframe获取多行图

2024-06-16 11:26:37 发布

您现在位置:Python中文网/ 问答频道 /正文

下面示例中的nvd3折线图使用python列表作为数据源。但是如何从pandas数据帧中绘制多行而不显式地声明列,例如pandas plot中:df.plot()df可以包含x列。在

from nvd3 import lineChart

# Open File for test
output_file = open('test_lineChart.html', 'w')
# ---------------------------------------
type = "lineChart"
chart = lineChart(name=type, x_is_date=False, x_axis_format="AM_PM")

xdata = list(range(0, 24))
ydata = [0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 4, 3, 3, 5, 7, 5, 3, 16, 6, 9, 15, 4, 12]
ydata2 = [9, 8, 11, 8, 3, 7, 10, 8, 6, 6, 9, 6, 5, 4, 3, 10, 0, 6, 3, 1, 0, 0, 0, 1]

kwargs1 = {'color': 'black'}
kwargs2 = {'color': 'red'}
extra_serie = {"tooltip": {"y_start": "There is ", "y_end": " calls"}}
chart.add_serie(y=ydata, x=xdata, name='sine', extra=extra_serie, **kwargs1)
extra_serie = {"tooltip": {"y_start": "", "y_end": " min"}}
chart.add_serie(y=ydata2, x=xdata, name='cose', extra=extra_serie, **kwargs2)

chart.buildhtml()

output_file.write(chart.htmlcontent)

# close Html file
output_file.close()

如何使用nvd3从该数据帧绘图:

^{pr2}$

Tags: 数据nametestpandasdfoutputplottype
1条回答
网友
1楼 · 发布于 2024-06-16 11:26:37

IIUC,chart将数据取为list,因此您必须将index和{}数据转换为list(假设您的column名称分别为col1和{}:

def plot_nvd3(df, ydata='col1', ydata2='col2'):
    # Open File for test
    output_file = open('test_lineChart.html', 'w')
    #                    -
    type = "lineChart"
    chart = lineChart(name=type, x_is_date=False, x_axis_format="AM_PM")

    xdata = df.index.tolist()
    ydata = df[ydata].tolist()
    ydata2 = df[ydata2].tolist()

    kwargs1 = {'color': 'black'}
    kwargs2 = {'color': 'red'}
    extra_serie = {"tooltip": {"y_start": "There is ", "y_end": " calls"}}
    chart.add_serie(y=ydata, x=xdata, name='sine', extra=extra_serie, **kwargs1)
    extra_serie = {"tooltip": {"y_start": "", "y_end": " min"}}
    chart.add_serie(y=ydata2, x=xdata, name='cose', extra=extra_serie, **kwargs2)

    chart.buildhtml()

    output_file.write(chart.htmlcontent)

    # close Html file
    output_file.close()

使用方法如下:

^{pr2}$

我没有检查nvd3如何与DateTimeIndex一起工作,以防df = df.set_index('datetime')产生一个。在

相关问题 更多 >