【问题标题】:Python: want to create scatter chart in Excel using pandas and xlsxwriterPython:想在 Excel 中使用 pandas 和 xlsxwriter 创建散点图
【发布时间】:2017-08-23 19:29:39
【问题描述】:

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

【问题讨论】:

  • 嗨汤姆,也许我没有很好地表达这个问题。基本上我希望图表在 Excel 中完成,作为“平滑线散点图”。
  • 这就是为什么我只是建议复制并没有关闭它:)

标签: python excel matplotlib


【解决方案1】:

你差不多了,你只需要指定图表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]})

输出:

【讨论】:

  • # 创建图表对象。 chart = workbook.add_chart({'type': 'scatter', 'subtype': 'smooth'}) # 配置第一个系列。 chart.add_series({ 'name': '=Sheet1!$A$1', 'categories': '=Sheet1!$A$2:$A$23', 'values': '=Sheet1!$B$2:$B$23 ', })
猜你喜欢
  • 1970-01-01
  • 2020-04-13
  • 2017-07-29
  • 1970-01-01
  • 1970-01-01
  • 2015-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多