python plotly交互图转静态图片

说明

在jupyter中,plotly直接生成的交互图有时候会过大,导致ipynb文件很大,这时候可以使用如下代码转为静态图片。

from IPython.display import Image

def px_to_png(fig):
    # fig为plotly生成的图片
    fig = fig.update_layout(font_family="SimHei") # 设置中文字体,防止中文乱码,可更换为其他,但是需要优先安装中文字体。安装步骤见下面。
    img_bytes = fig.to_image(format="png") 
    img = Image(img_bytes)            
    # display(img)
    return img

中文字体安装

画图的时候,如果图例等存在中文,有可能会产生乱码,所以需要优先安装中文字体,这里给出在linux下安装SimHei字体的步骤。


fc-list :lang=zh  # 查看是否系统有中文字体
sudo yum install -y fontconfig mkfontscale # 安装字体配置软件
sudo cp SimHei.ttf /usr/share/fonts # SimHei.ttf自行百度搜索下载,https://github.com/StellarCN/scp_zh/blob/master/fonts/SimHei.ttf
mkfontscale       # 扩展字体
mkfontdir         # 新增字体目录
fc-cache -fv      # 刷新字体缓存
fc-list :lang=zh  #查看安装好的中文字体 

猜你喜欢

转载自blog.csdn.net/lpfangle/article/details/127208854