Python:想要使用pandas和xlsxwriter在Excel中创建散点图

时间:2017-08-23 09:33:46

标签: python excel matplotlib

嗨我下面有一些基本代码,其中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()

1 个答案:

答案 0 :(得分:0)

你几乎拥有它,你只需要指定图表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]})

输出:

enter image description here