首页 > 解决方案 > 如何使用数据框和python将绘图饼图显示到创建表旁边的excel文件中

问题描述

我有一个 python 脚本,它通过向现有表中添加一个新字段来预测数据帧正面和负面情绪的情绪分析。我绘制了正面和负面情绪百分比的饼图。最后,它将结果保存到 excel 文件中。

我想在表格旁边添加这个绘制饼图。

怎么做这个任务?

代码:

import pandas as pd
import matplotlib.pyplot as plt

    test_twtr = pd.read_excel("F:/AIenv/sentiment_analysis/20200717_100219_Sentiment - Copy.xlsx",names=col_names)
    
    test_twtr['processed_TEXT'] = test_twtr['TRANSLATION'].apply(processTweet)
    test_twtr_preds = LR_Model.predict(test_twtr['processed_TEXT'])
    def_test_twtr_preds = test_twtr.copy()
    positives = def_test_twtr_preds["predictions"][def_test_twtr_preds.predictions ==1]
    negatives = def_test_twtr_preds["predictions"][def_test_twtr_preds.predictions ==0]
    
    slices_tweets = [format(100*len(positives)/len(def_test_twtr_preds["predictions"])), format(100*len(negatives)/len(def_test_twtr_preds["predictions"]))]
    analysis = ['pos', 'neg']
    colors = ['yellow', 'red']
    plt.pie(slices_tweets, labels=analysis, startangle=90, autopct='%.1f%%',colors = colors)
    plt.title("Percentage of sentiment analysis")
    plt.show()
    
    df_test_tweet_preds_to_csv = def_test_twtr_preds.to_csv(outputPath, index = False, header=True)
     

标签: pythonexcelpandasmatplotlib

解决方案


我认为您不能使用 Pandas 直接将 matplot 图像插入 Excel 文件。您可以做一些解决方法:

  1. 保存图像
  2. 将数据导出到excel
  3. 用 xlsxwriter 打开 excel 文件
  4. 并将图像加载到 Excel 文件中。并再次保存

有关如何将图像插入 excel 的信息,请参见: https ://xlsxwriter.readthedocs.io/example_images.html


推荐阅读