【问题标题】:Multiline chart from dataframe using nvd3使用 nvd3 来自数据框的多线图
【发布时间】:2016-06-20 08:50:05
【问题描述】:

以下示例中的 nvd3 折线图使用 python 列表作为数据源。但是如何在不明确说明列的情况下从 pandas 数据框中绘制多线,例如在 pandas 图中: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 从此数据框中进行绘图:

df = pd.DataFrame(data)
df = df.set_index('datetime')
fig, ax = plt.subplots()
df.plot(ax=ax, marker='o')

【问题讨论】:

    标签: python pandas nvd3.js


    【解决方案1】:

    IIUC,chart 将数据作为list,因此您必须将您的indexcolumn 数据转换为list 像这样(假设您的column 名称是col1col2分别:

    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()
    

    用途:

    plot_nvd3(df, 'col1', 'col2')
    

    我还没有检查nvd3 如何与DateTimeIndex 一起使用,以防您的df = df.set_index('datetime') 产生一个。

    【讨论】:

      猜你喜欢
      • 2015-12-20
      • 1970-01-01
      • 2021-11-15
      • 1970-01-01
      • 2017-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-18
      相关资源
      最近更新 更多