【问题标题】:Interactive Plot of Pandas Data-frame Color coding based on a group from a ColumnPandas Dataframe 的交互式绘图基于列中的一组颜色编码
【发布时间】:2019-02-10 22:29:56
【问题描述】:

我有一个示例熊猫数据框如下:

      day  id     cnt
      2   catx     4
      2   kagm     3
      2   dyrt     5
      3   catx     3
      3   kagm     3
      3   dyrt     4
      5   catx     2
      5   kagm     2
      5   dyrt     2  

我想绘制散点数据 cnt (y) vs day(x),其中的点将根据 id 列标记(彩色/图例)

现在这在 seaborn/matplotlib 中非常简单,我知道可以绘制它并且可以将绘图保存到文件中。

但是,我希望使用 plotly/bokeh/d3/mp3ld 等进行交互式绘图,最后,将该绘图放入 url(我选择或也许是一个基于情节的帐户)。我的目标也是具有悬停功能,当我将光标移到特定光标点上时,它将向我显示点的值。

我已经尝试使用 ColumnDataSource 的袖扣散景/绘图 以及尝试获取绘图的所有方法。但是,没有得到我正在寻找的任何东西。我可以从专家那里获得一些帮助吗?感谢期待。

【问题讨论】:

  • 解决这些问题后您还有其他要求吗?
  • 谢谢。不,我只想将它们发布到我想要的 url,其中包含交互功能和颜色编码。无需进一步处理。

标签: python-3.x pandas d3.js plotly bokeh


【解决方案1】:

此代码按照您要求的方式绘制数据。我为您的数据框中的每个类别创建了一个新的数据框,因此交互式图例也可以使用。使用唯一类别数的长度生成一个包含十六进制颜色字符串的数组,并将其添加到数据框中,为每个类别赋予其自己的颜色。

#!/usr/bin/python3

import pandas as pd
from bokeh.models import ColumnDataSource
from bokeh.palettes import all_palettes
from bokeh.plotting import figure, output_file, show

data = {'day': [2, 2, 2, 3, 3, 3, 5, 5, 5], 'id': ['catx', 'kagm', 'dyrt', 'catx', 'kagm', 'dyrt', 'catx', 'kagm', 'dyrt'], 'cnt': [4, 3, 5, 3, 3, 4, 2, 2, 2]}
df = pd.DataFrame.from_dict(data)

output_file('plot.html')
tooltips = [
    ("day", "@day"),
    ("id", "@$name"),
    ("count", "@cnt")]
p = figure(tooltips=tooltips, plot_width=800, plot_height=800)

sources = []
colors = all_palettes['Viridis'][len(set(df['id'].tolist()))]
pd.options.mode.chained_assignment = None #Supress false positive warning
for ID, color in zip(set(df['id'].tolist()), colors):
    dfSubset = df.loc[df['id'] == ID]
    dfSubset['color'] = color
    sources.append(ColumnDataSource(dfSubset))
    p.circle(x = 'day', y = 'cnt', legend = 'id', color = 'color', name = 'id', alpha = 0.5, size = 15, source = sources[-1])

p.legend.click_policy="hide"

show(p)

【讨论】:

    猜你喜欢
    • 2018-04-16
    • 2013-12-26
    • 2012-04-17
    • 2016-02-06
    • 2020-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    相关资源
    最近更新 更多