2017-10-06 84 views
0

我試圖在一個Django項目中使用pandas-highcharts;我能夠生成圖表,但數據不會被繪製,所以我猜測我的熊貓數據框格式不正確,或者我沒有使用正確的方法來呈現模板。如何格式化一個熊貓數據框以便在Django中與熊貓一起使用

結果: resulting highchart graph

我的數據框:

      Entrée d'eau - Archimède - 0013A2004166CFCD 
timestamp                
2016-12-23 00:05:18+00:00           29.0 
2016-12-23 00:05:27+00:00           29.0 
2016-12-23 00:05:37+00:00           29.0 
2016-12-23 00:05:47+00:00           29.0 
2016-12-23 00:05:58+00:00           29.0 

我的觀點:

from django.shortcuts import render 
from data.models import Value 
import pandas as pd 
from pandas_highcharts.core import serialize 

# [...] 

df = pd.DataFrame.from_records(
    Value.objects.filter(device=a).values("timestamp", "leak_value")) 

df.dropna(inplace=True) # not sure about this 
df.set_index("timestamp", inplace=True) 
df.sort_index(inplace=True) 
df = df.truncate(
    before=pd.to_datetime(request.POST.get("start")), 
    after=pd.to_datetime(request.POST.get("stop"))) 
df = df.rename(
    index=str, 
    columns={"leak_value": "{} - {} - {}".format(
     Room.objects.filter(unit=unit_sel).get(device=a), 
     Device.objects.get(address=a).devicetype, 
     a)}) 

print(df.head()) # DEBUG 

chart = serialize(
    df=df, 
    render_to='Leak Values', 
    title="Leak Values", 
    output_type='json') 

return render(request, "leak_chart.html", context={"chart": chart}) 

我的模板(包括我在base.html文件jQuery和highcharts):

{% extends "base.html" %} 

{% block body %} 

    {% load staticfiles %} 

    <div id="Leak Values"></div> 

    <script type="text/javascript"> 
     new Highcharts.Chart({{chart|safe}}); 
    </script> 

{% endblock %} 

頁面的源代碼: https://pastebin.com/EkJYQPLQ

通過我還沒有發現大熊貓,highcharts一個標籤,我不認爲我有特權創建它的方式。我使用的是熊貓,highcharts 0.5.2

編輯:這似乎question有關,但我不能回答適用於我的具體情況。

+0

你可以檢查傳遞給圖表leak_chart.html的格式是什麼。??它甚至是一個JSON格式.. ?? – MoChen

+0

該系列應該是這樣的:'系列:[{ \t名: '簡', \t數據:[1,0,4] },{ \t名: '約翰', \t數據:[5 ,[7,3] }]'這是我在生成圖形之後從頁面源中提取的內容:''series「:[{0} {0} [''''''''」'data「:[ \t \t [」2016-12-23 00:05 :18 + 00:00「,29.0], \t \t [」2016-12-23 00:05:27 + 00:00「,29.0], \t \t [」2016-12-23 19:11:34 +00:00「,29.0] \t], \t 「Y軸」:0, \t 「名」: 「ENTR \ u00e9e D'淡 - Archim \ u00e8de - 0013A2004166CFCD」 }]' –

回答

0

打開了所有我不得不改變是增加「use_index =假」,現在我的數據顯示:

chart = serialize(
      df=final_df, 
      render_to='Leak Values', 
      title="Leak Values", 
      use_index=False, 
      output_type='json') 

然而時間戳沒有顯示,所以我想我將不得不作出大熊貓正如@Kamil Kulig所建議的那樣,高分辨率會將它們識別爲日期時間。

1

Highcharts中的類別用作軸'標籤的值。如果你想指定點的座標(X,Y或Z)的類別,你應該使用一個類指數從categories陣列:

xAxis: { 
    categories: ['cat1', 'cat2'] 
} 

series: [{ 
    data: [ 
    [0 /*refers to the 'cat1' category */, someValue], 
    [1,/*refers to the 'cat1' category */, someValue] 
    ] 
}] 

我認爲,在這個例子中,更好的方法是使用datetime類型x軸(http://api.highcharts.com/highcharts/xAxis.type)並將您的x值轉換爲時間戳。在這種情況下,根本不需要使用類別。

+0

謝謝你的回答,這使我準確地找到如何修復我的代碼以使用pandas-highcharts。 –