【问题标题】:Matplotlib: Plot the result of an SQL queryMatplotlib:绘制 SQL 查询的结果
【发布时间】:2023-03-25 10:51:01
【问题描述】:
from sqlalchemy import create_engine
import _mssql
from matplotlib import pyplot as plt

engine = create_engine('mssql+pymssql://**:****@127.0.0.1:1433/AffectV_Test')
connection = engine.connect()
result = connection.execute('SELECT Campaign_id, SUM(Count) AS Total_Count FROM Impressions GROUP BY Campaign_id')
for row in result:
   print row

connection.close()

以上代码生成一个数组:

(54ca686d0189607081dbda85', 4174469)
(551c21150189601fb08b6b64', 182)
(552391ee0189601fb08b6b73', 237304)
(5469f3ec0189606b1b25bcc0', 4231)
(54e35ea90189603f6b557571', 1362847)
(54f05c140189600828ee23f9', 570635)

如何使用 matplotlib 将此结果绘制为条形图?不知道如何绘制 for 循环的结果。

【问题讨论】:

  • 两个轴是什么?
  • @Noob 上述数组,形式为(x,y)
  • x 是我可以理解的字符串。你打算如何绘制它?
  • X轴的字符串和Y轴对应的numerinc值。
  • 抱歉忘了说:我希望它是一个简单的条形图。

标签: python sql matplotlib plot


【解决方案1】:

将此作为入门代码:

import numpy as np
import matplotlib.pyplot as plt
from sqlalchemy import create_engine
import _mssql

fig = plt.figure()
ax = fig.add_subplot(111)


engine = create_engine('mssql+pymssql://**:****@127.0.0.1:1433/AffectV_Test')
connection = engine.connect()
result = connection.execute('SELECT Campaign_id, SUM(Count) AS Total_Count FROM Impressions GROUP BY Campaign_id')


## the data

data = []
xTickMarks = []

for row in result:
   data.append(int(row[1]))
   xTickMarks.append(str(row[0]))

connection.close()


## necessary variables
ind = np.arange(len(data))                # the x locations for the groups
width = 0.35                      # the width of the bars

## the bars
rects1 = ax.bar(ind, data, width,
                color='black',
                error_kw=dict(elinewidth=2,ecolor='red'))


# axes and labels
ax.set_xlim(-width,len(ind)+width)
ax.set_ylim(0,45)


ax.set_ylabel('Y LABEL')
ax.set_xlabel('X LABEL')
ax.set_title('TITLE_HERE')

ax.set_xticks(ind+width)
xtickNames = ax.set_xticklabels(xTickMarks)
plt.setp(xtickNames, rotation=45, fontsize=10)


plt.show()

【讨论】:

  • 完美!正是我想要的!我会从这里拿走!非常感谢。
  • 我在第 31 行收到此错误AssertionError: incompatible sizes: argument 'height' must be length 5 or scalarerror_kw=dict(elinewidth=2,ecolor='red')
  • @TauseefHussain - 已编辑!立即尝试。
  • 现在很好用。我可能需要更改 Y 轴的步数。目前它是 0 到 45,这在该图中显然没有意义。我应该阅读文档:)
  • 尝试将 ax.set_ylim(0,45) 更改为 ax.set_ylim(0,max(data))
猜你喜欢
  • 2017-12-13
  • 1970-01-01
  • 2018-09-06
  • 2011-03-08
  • 1970-01-01
  • 1970-01-01
  • 2019-12-27
  • 2023-03-10
  • 2011-03-24
相关资源
最近更新 更多