【问题标题】:Unable to use Bokeh and Panda to read a csv and plot it无法使用 Bokeh 和 Pandas 读取 csv 并绘制它
【发布时间】:2019-01-03 11:27:23
【问题描述】:

我正在尝试从一个包含两列的简单 CSV 文件绘制折线图,​​使用 Bokeh 进行数据可视化,使用 Panda 读取 CSV 并处理数据。但是,我似乎无法将使用 pandas 导入的数据传递给 Bokeh 来绘制我的折线图。

这是在我的计算机上本地运行的。我已经尝试并调试了代码的每个部分,当我将数据从熊猫传递到散景时,似乎出现了唯一的问题。

我已尝试打印从 csv 中选择的列,以检查是否也选择了整个列。

#Requirements for App
from bokeh.plotting import figure, output_file, show
import pandas as pd
from bokeh.models import ColumnDataSource

#Import data-->Weight measurements over a period of time [ STUB ]
weight = pd.read_csv("weight.csv")

#Define parameters
x=weight["Date"]
y=weight["Weight"]

#Take data  and present in a graph
output_file("test.html")
p = figure(plot_width=400, plot_height=400)
p.line(x,y,line_width=2)
show(p)

我希望得到一个绘制每天每个重量条目的折线图,但我得到一个空白图。

【问题讨论】:

    标签: python bokeh


    【解决方案1】:

    这应该可行。 Pandas 不知道它正在处理日期,因此您必须使用 pd.to_datetime() 指定它。

    #!/usr/bin/python3
    from bokeh.plotting import figure, output_file, show
    import pandas as pd
    from bokeh.models import DatetimeTickFormatter, ColumnDataSource
    
    #Import data-->Weight measurements over a period of time [ STUB ]
    weight = pd.read_csv("weight.csv")
    
    #Define parameters
    weight["Date"] = pd.to_datetime(weight['Date'])
    weight["Weight"] = pd.to_numeric(weight['Weight'])
    
    source = ColumnDataSource(weight)
    
    #Take data  and present in a graph
    output_file("test.html")
    p = figure(plot_width=400, plot_height=400, x_axis_type='datetime')
    p.line(x='Date',y='Weight',line_width=2, source=source)
    p.xaxis.formatter=DatetimeTickFormatter(
        minutes=["%M"],
        hours=["%H:%M"],
        days=["%d/%m/%Y"],
        months=["%m/%Y"],
        years=["%Y"]
    )
    show(p)
    

    【讨论】:

    • 非常感谢@Jasper!这帮助我得到了我想要的图表。只是好奇,为什么要将导入的 csv 转换为 ColumnDataSource。这有必要吗?如果有,它的用途是什么?
    • 在这种情况下不需要使用 ColumnDataSource,它用于使用 Bokeh 进行更高级的可视化(在悬停时显示数据、流数据等...)。我看到你已经导入了它,所以我想也可以展示一下你应该如何使用它。
    • 我明白了!非常感谢贾斯珀 :)
    • @Jasper 非常感谢。这是旧的,但它在 2021 年救了我 :)
    • @Grantx 很高兴听到:)
    猜你喜欢
    • 2015-10-09
    • 2019-03-18
    • 1970-01-01
    • 2021-06-05
    • 2019-11-13
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    • 1970-01-01
    相关资源
    最近更新 更多