pandas 使用散景设置初始缩放

3okqufwl  于 2023-08-01  发布在  其他
关注(0)|答案(2)|浏览(121)

假设我从文档中获得了以下条形图:

from bokeh.io import show, output_notebook
from bokeh.plotting import figure
output_notebook()

字符串

  • 下面是分类值(或因子)的列表
fruits = [`Apples, Pears`, `Nectarines`, `Plums`, `Grapes`, `Strawberries`]

  • 将x_range设置为上面的类别列表
p = figure(x_range=fruits, plot_height=250, title=“Fruit Counts”)

  • 分类值也可用作坐标
p.vbar(x=fruits, top=[5, 3, 4, 2, 4, 6], width=0.9)

  • 设置一些属性以使图看起来更好
p.xgrid.grid_line_color = None
p.y_range.start = 0
show(p)


如何设置它,使初始缩放仅显示前四个类别(但用户可以平移以查看其他两个,缩小等)?
我尝试修改x_range值,但看起来x_range需要等于fruits。

polhcujo

polhcujo1#

我正在考虑的一个选项是添加一个滑块来过滤数据框架中的行。
你可以在jupyter笔记本中尝试以下代码:

from bokeh.io import show, output_notebook
from bokeh.models import ColumnDataSource, CustomJS, Slider, DataRange1d
from bokeh.plotting import figure
import pandas as pd
from bokeh.layouts import column
output_notebook()

def create_plots(doc):
    
    # Create dataframe
    df = pd.DataFrame({
        'fruits': ['Apples', 'Pears', 'Nectarines', 'Plums', 'Grapes', 'Strawberries'],
        'top': [5, 3, 4, 2, 4, 6]
    })
    fruits=list(df['fruits'])
    max_top = max(df['top'])
    
    # Create Column Data Source
    source = ColumnDataSource(data=df)
    
    # Create figure
    p = figure(x_range=fruits, plot_height=250, title='Fruit Counts',
               y_range=DataRange1d(0, max_top + 1, only_visible=True),  # with DataRange1d + only_visible=True, the 
               # y scale will be updated automatically depending on the data displayed on the chart
              )
    p.vbar(x='fruits', top='top', width=0.9, source=source)

    p.xgrid.grid_line_color = None
    p.y_range.start = 0

    # Create slider widget
    slider = Slider(start=1, end=max_top, value=max_top, step=1, title="Slider example - current value")
    
    # Update chart with widget value
    slider.js_on_change("value", CustomJS(code="""
        console.log('slider: value=' + this.value, this.toString())
    """))  # I'm not comfortable with javascript but this code can be found in Bokeh documentation: 
    # https://docs.bokeh.org/en/latest/docs/user_guide/interaction/widgets.html#slider

    def update_data(df, max_index):
        # update the Column Data Source with the filtered data
        df = df[df.index <= max_index]
        source.data = df
        
        # update the x axis - hidden fruits should not be displayed on the x axis
        p.x_range.factors = list(df['fruits'])

    def update(attr, old, new):
        max_index_to_display = slider.value - 1
        update_data(df, max_index_to_display)

    slider.on_change('value', update) # call the update funtion everytime the slider is clicked on

    # Layout
    doc.add_root(column(slider, p))

show(create_plots)

字符串

kpbpu008

kpbpu0082#

不能将CategoricalAxisFactorRange一起使用并设置x_range,因为startend是只读属性.
但也有一些变通办法,下面列出了两个。

使用CustomJSTickFormatter

在散景版本3.0.0中,添加了CustomJSTickFormatter。这样就可以使用普通的LinearRange并格式化记号。“使用这种方法,您可以根据自己的喜好设置x_range

from bokeh.models import CustomJSTickFormatter, Range1d
from bokeh.plotting import figure, show, output_notebook
output_notebook()

fruits = ["Apples", "Pears", "Nectarines", "Plums", "Grapes", "Strawberries"]

x = list(range(len(fruits)))
y = [5, 3, 4, 2, 4, 6]

p = figure(height=250, title="Fruit Counts")
p.x_range = Range1d(-0.5, 3.5, bounds=(-0.5, 4.5))
p.y_range = Range1d(0, 7)
p.vbar(x=x, top=y, width=0.9)
p.xgrid.grid_line_color = None
p.xaxis.formatter = CustomJSTickFormatter(
    code="""
    var new_tick=  tick.toFixed(2)
    const fruits = ["Apples", "Pears", "Nectarines", "Plums", "Grapes", "Strawberries"]
    const range = [...Array(fruits.length).keys()]
    if( tick in range )
        new_tick= fruits[tick]
    else
        new_tick= ''
    return new_tick
    """
)
p.xaxis.minor_tick_line_color = None
p.xaxis.axis_label_text_color  = None

show(p)

字符串

使用FixedTickermajor_label_overrides

使用FixedTicker,您可以将记号设置到您想要的位置,而major_label_overrides为您提供了非常精确地设置标签文本的机会。在3.0.0发行版之前也可以使用。

from bokeh.models import FixedTicker, Range1d
from bokeh.plotting import figure, show, output_notebook
output_notebook()

fruits = ["Apples", "Pears", "Nectarines", "Plums", "Grapes", "Strawberries"]

x = list(range(len(fruits)))
y = [5, 3, 4, 2, 4, 6]

p = figure(height=250, title="Fruit Counts")
p.x_range = Range1d(-0.5, 3.5, bounds=(-0.5, 4.5))
p.y_range = Range1d(0, 7)
p.vbar(x=x, top=y, width=0.9)
p.xgrid.grid_line_color = None
p.xaxis.ticker = FixedTicker(
    desired_num_ticks=len(fruits),
    num_minor_ticks = 0,
    ticks=x
)
p.xaxis.major_label_overrides = {i: label for i, label in zip(x, fruits)}

show(p)


视觉结果应相同,初始视图如下所示:


的数据

相关问题