簡體   English   中英

python bokeh,如何制作相關圖?

[英]python bokeh, how to make a correlation plot?

如何在散景中制作相關熱圖?

import pandas as pd
import bokeh.charts

df = pd.util.testing.makeTimeDataFrame(1000)
c = df.corr()

p = bokeh.charts.HeatMap(c) # not right

# try to make it a long form
# (and it's ugly in pandas to use 'index' in melt)

c['x'] = c.index
c = pd.melt(c, 'x', ['A','B','C','D'])

# this shows the right 4x4 matrix, but values are still wrong
p = bokeh.charts.HeatMap(c, x = 'x', y = 'variable', values = 'value') 

順便說一句,我可以在側面制作一個顏色條,而不是情節中的圖例嗎? 以及如何選擇顏色范圍/映射,例如深藍色(-1)到白色(0)到深紅色(+1)?

所以我想我可以提供一個基線代碼來幫助你使用上面的答案和一些額外的預處理的組合來完成你的要求。

假設您已經加載了一個數據幀df (在本例中為UCI Adult Data )並計算了相關系數( p_corr )。

import bisect
#
from math import pi
from numpy import arange
from itertools import chain
from collections import OrderedDict
#
from bokeh.palettes import RdBu as colors  # just make sure to import a palette that centers on white (-ish)
from bokeh.models import ColorBar, LinearColorMapper

colors = list(reversed(colors[9]))  # we want an odd number to ensure 0 correlation is a distinct color
labels = df.columns
nlabels = len(labels)

def get_bounds(n):
    """Gets bounds for quads with n features"""
    bottom = list(chain.from_iterable([[ii]*nlabels for ii in range(nlabels)]))
    top = list(chain.from_iterable([[ii+1]*nlabels for ii in range(nlabels)]))
    left = list(chain.from_iterable([list(range(nlabels)) for ii in range(nlabels)]))
    right = list(chain.from_iterable([list(range(1,nlabels+1)) for ii in range(nlabels)]))
    return top, bottom, left, right

def get_colors(corr_array, colors):
    """Aligns color values from palette with the correlation coefficient values"""
    ccorr = arange(-1, 1, 1/(len(colors)/2))
    color = []
    for value in corr_array:
        ind = bisect.bisect_left(ccorr, value)
        color.append(colors[ind-1])
    return color

p = figure(plot_width=600, plot_height=600,
           x_range=(0,nlabels), y_range=(0,nlabels),
           title="Correlation Coefficient Heatmap (lighter is worse)",
           toolbar_location=None, tools='')

p.xgrid.grid_line_color = None
p.ygrid.grid_line_color = None
p.xaxis.major_label_orientation = pi/4
p.yaxis.major_label_orientation = pi/4

top, bottom, left, right = get_bounds(nlabels)  # creates sqaures for plot
color_list = get_colors(p_corr.values.flatten(), colors)

p.quad(top=top, bottom=bottom, left=left,
       right=right, line_color='white',
       color=color_list)

# Set ticks with labels
ticks = [tick+0.5 for tick in list(range(nlabels))]
tick_dict = OrderedDict([[tick, labels[ii]] for ii, tick in enumerate(ticks)])
# Create the correct number of ticks for each axis 
p.xaxis.ticker = ticks
p.yaxis.ticker = ticks
# Override the labels 
p.xaxis.major_label_overrides = tick_dict
p.yaxis.major_label_overrides = tick_dict

# Setup color bar
mapper = LinearColorMapper(palette=colors, low=-1, high=1)
color_bar = ColorBar(color_mapper=mapper, location=(0, 0))
p.add_layout(color_bar, 'right')

show(p)

如果類別是整數編碼的,這將導致以下圖(這是一個可怕的數據示例):

散景中的 Pearson 相關系數熱圖

在現代散景中,您應該使用bokeh.plotting界面 您可以在圖庫中看到使用此界面生成的分類熱圖示例:

http://docs.bokeh.org/en/latest/docs/gallery/categorical.html


關於圖例,對於這樣的顏色圖,您實際上需要一個離散的ColorBar而不是Legend 這是一項新功能,將出現在本周晚些時候(今天的日期:2016-08-28)即將發布的0.12.2版本中。 這些新的顏色條注釋可以位於主繪圖區域之外。

GitHub repo 中還有一個示例:

https://github.com/bokeh/bokeh/blob/master/examples/plotting/file/color_data_map.py

請注意,最后一個示例還使用另一個新功能在瀏覽器中進行顏色映射,而不必在 python 中預先計算顏色。 基本上所有在一起看起來像:

# create a color mapper with your palette - can be any list of colors
mapper = LinearColorMapper(palette=Viridis3, low=0, high=100)

p = figure(toolbar_location=None, tools='', title=title)
p.circle(
    x='x', y='y', source=source

    # use the mapper to colormap according to the 'z' column (in the browser)
    fill_color={'field': 'z', 'transform': mapper},  
)

# create a ColorBar and addit to the side of the plot
color_bar = ColorBar(color_mapper=mapper, location=(0, 0))
p.add_layout(color_bar, 'right')

還有更復雜的選項,例如,如果您想更仔細地控制顏色欄上的刻度,您可以像在普通Axis上一樣添加自定義代碼或刻度格式,以實現以下目的:

在此處輸入圖片說明

目前尚不清楚您的實際需求是什么,所以我只是提到這一點,以防萬一它是有用的。


最后,Bokeh 是一個大型項目,找到最好的方法通常需要詢問更多信息和背景,一般來說,進行討論。 這種協作幫助似乎對 SO 不屑一顧(它們“不是真正的答案”),因此我鼓勵您也隨時查看項目 Discourse以獲得幫助。

我嘗試使用 Bokeh 庫創建交互式相關圖。 該代碼是 SO 和其他網站上可用的不同解決方案的組合。 在上面的解決方案中 bigreddot 已經詳細解釋了事情。 相關熱圖代碼如下:

import pandas as pd
from bokeh.io import output_file, show
from bokeh.models import BasicTicker, ColorBar, LinearColorMapper, ColumnDataSource, PrintfTickFormatter
from bokeh.plotting import figure
from bokeh.transform import transform
from bokeh.palettes import Viridis3, Viridis256
# Read your data in pandas dataframe
data = pd.read_csv(%%%%%Your Path%%%%%)
#Now we will create correlation matrix using pandas
df = data.corr()

df.index.name = 'AllColumns1'
df.columns.name = 'AllColumns2'

# Prepare data.frame in the right format
df = df.stack().rename("value").reset_index()

# here the plot :
output_file("CorrelationPlot.html")

# You can use your own palette here
# colors = ['#d7191c', '#fdae61', '#ffffbf', '#a6d96a', '#1a9641']

# I am using 'Viridis256' to map colors with value, change it with 'colors' if you need some specific colors
mapper = LinearColorMapper(
    palette=Viridis256, low=df.value.min(), high=df.value.max())

# Define a figure and tools
TOOLS = "box_select,lasso_select,pan,wheel_zoom,box_zoom,reset,help"
p = figure(
    tools=TOOLS,
    plot_width=1200,
    plot_height=1000,
    title="Correlation plot",
    x_range=list(df.AllColumns1.drop_duplicates()),
    y_range=list(df.AllColumns2.drop_duplicates()),
    toolbar_location="right",
    x_axis_location="below")

# Create rectangle for heatmap
p.rect(
    x="AllColumns1",
    y="AllColumns2",
    width=1,
    height=1,
    source=ColumnDataSource(df),
    line_color=None,
    fill_color=transform('value', mapper))

# Add legend
color_bar = ColorBar(
    color_mapper=mapper,
    location=(0, 0),
    ticker=BasicTicker(desired_num_ticks=10))

p.add_layout(color_bar, 'right')

show(p)

參考資料:

[1] https://docs.bokeh.org/en/latest/docs/user_guide.html

[2] 來自 Pandas 混淆矩陣的散景熱圖

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM