我使用 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)
我编辑了这个答案,因为我刚刚找到了解决方案的 2/2 部分:
当我仅使用上面的代码时,绘图是半对数(好的!),但 x 轴被翻转(镜像)!!!
我找到的解决方案是明确地重新定义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)
关于python - 使用 matplotlib 绘制 semilogx,然后将其转换为 Bokeh,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33281642/