簡體   English   中英

Python:想要使用熊貓和xlsxwriter在Excel中創建散點圖

[英]Python: want to create scatter chart in Excel using pandas and xlsxwriter

嗨,我有一些基本代碼,在x軸上有M值,在y軸上有N值。

我希望能夠創建通過使用matplotlib而在Microsoft Excel中獲得的圖表。 這可能嗎?

我嘗試過:chart = workbook.add_chart({'type':'scatter'}),但沒有成功。 是否有其他“類型”可以讓我獲得與在matplotlib中獲得的圖表類似的圖表?

M = [-2.29, 33.63, 66.52, 96.37, 123.10, 146.79, 167.49, 185.20, 199.94,   211.68, 220.44, 226.22, 229.02, 230.25, 227.07, 220.91, 211.77, 199.64, 184.53, 164.48, 141.67, 0.00]
N = [-292.20, 6.65, 305.47, 604.25, 901.94, 1198.81, 1495.67, 1792.54, 2089.41, 2386.27, 2683.14, 2980.01, 3276.88, 3561.89, 3858.76, 4155.63, 4452.49, 4749.36, 5046.23, 5361.80, 5666.67, 5666.67]


import pandas as pd

# Create a Pandas dataframe from some data for M.
df1 = pd.DataFrame({'M (kNm)': [M[0], M[1], M[2],
 M[3], M[4], M[5], M[6], M[7],
  M[8], M[9], M[10], M[11], M[12],
   M[13], M[14], M[15], M[16], M[17],
    M[18], M[19], M[20], M[21]]})

# Create a Pandas dataframe from some data for N.
df2 = pd.DataFrame({'N (kN)': [N[0], N[1], N[2],
 N[3], N[4], N[5], N[6], N[7],
  N[8], N[9], N[10], N[11], N[12],
   N[13], N[14], N[15], N[16], N[17],
    N[18], N[19], N[20], N[21]]})

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('MN_example.xlsx', engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object.
df1.to_excel(writer, sheet_name='Sheet1', index=False)
df2.to_excel(writer, sheet_name='Sheet1', startcol=1, index=False)

# Get the xlsxwriter workbook and worksheet objects.
workbook  = writer.book
worksheet = writer.sheets['Sheet1']

# Create a chart object.
chart = workbook.add_chart({'type': 'scatter'})

# Configure the series of the chart from the dataframe data.
chart.add_series({'values': '=Sheet1!$A$2:$B$23'})

# Insert the chart into the worksheet.
worksheet.insert_chart('D2', chart)

# Close the Pandas Excel writer and output the Excel file.
writer.save()

import matplotlib.pyplot as plt

plt.plot(M, N, linewidth=2)


plt.show()

您幾乎已經擁有了它,您只需要指定圖表subtype並指定應該在其上繪制圖表的數據categories

將圖表初始化和配置替換為以下內容,您將獲得所需的內容:

# Create a chart object.
chart = workbook.add_chart({'type': 'scatter',
                            'subtype': 'smooth'})

# Configure the series of the chart from the dataframe data.
chart.add_series({
    'categories': ['Sheet1', 1, 0, len(df2), 0],
    'values':     ['Sheet1', 1, 1, len(df2), 1]})

輸出:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM