Skip to main content
 首页 » 编程设计

python之使用 matplotlib 绘制 semilogx,然后将其转换为 Bokeh

2024年10月24日14cloudgamer

我使用 matplotlib 绘制了一个包含多条曲线的图形,然后尝试将其转换为 Bokeh :

import numpy as np 
import matplotlib.pyplot as plt 
from bokeh import mpl 
from bokeh.plotting import show, output_file 
 
 
num_plots = 6 
colormap = plt.cm.gist_ncar 
time = np.random.random_sample((300, 6)) 
s_strain = np.random.random_sample((300, 6)) 
 
def time_s_strain_bokeh(num_plots, colormap, time, s_strain): 
 
    plt.gca().set_color_cycle([colormap(i) for i in np.linspace(0, 0.9, num_plots)]) 
 
    plt.figure(2) 
    for i in range(0, num_plots): 
        plt.plot(time[:,i], s_strain[:,i]) 
    plt.grid(True) 
 
    # save it to bokeh 
    output_file('anywhere.html') 
    show(mpl.to_bokeh())     
 
time_s_strain_bokeh(num_plots, colormap, time, s_strain) 

它工作正常。但是,我想要一个 semilogx 图。当我将“for”循环中的 plt.plot 更改为 plt.semilogx 时,出现以下错误:

UnboundLocalError: local variable 'laxis' referenced before assignment 

如何将 x 轴更改为对数刻度?

请您参考如下方法:

我也遇到了同样的问题! 1/2 的解决方案是这样的(假设我的数据在一个名为 pd 的 Pandas 数据框中):

pd.plot(x='my_x_variable', y='my_y_variable)  
p = mpl.to_bokeh() 
p.x_mapper_type='log' # I found this property with p.properties_with_values() 
show(p) 

我编辑了这个 answare,因为我刚刚找到了解决方案的第 2/2 部分:

  1. 当我只使用上面的代码时,绘图是半对数的(好的!),但是 x 轴是翻转的(镜像的)!!!

  2. 我找到的解决方案是显式地重新定义 xlim:

    p.x_range.start=0.007 # 假设 pd['my_x_variable'] 从 0.007 开始 p.x_range.end=0.17 # 假设 pd['my_x_variable'] 结束于 0.17

有了这个,我的情节变得与 matplotlib 原始情节相同。最终代码如下所示:

pd.plot(x='my_x_variable', y='my_y_variable)  
p = mpl.to_bokeh() 
p.x_mapper_type='log'  
p.x_range.start= pd['my_x_variable'].iloc[1] # numpy start at 0, take care! 
p.x_range.end= pd['my_x_variable'].iloc[-1] 
show(p)