我正在尝试使用matplotlib创建一个多条形图。
from sqlalchemy import create_engine
import _mssql
from matplotlib import pyplot as plt
import numpy as np
engine = create_engine('mssql+pymssql://sa:california851101@127.0.0.1:1433/AffectV_Test')
connection = engine.connect()
result = connection.execute('SELECT pa.[Date],pa.[Type],(CAST((SUM(pa.Actions_Logged)/SUM(pi.Impressions_Served))*100 AS Decimal(4,4))) AS Daily_Action_Rate from Performance_Actions pa INNER JOIN Performance_Impressions pi ON pa.Alternative = pi.Alternative AND pa.[Date] = pi.[Date] GROUP BY [Type],pa.[Date] ORDER BY pa.[Date] ASC')
click = []
conversion = []
landing = []
xTickMarks = []
for row in result:
if row[1] == 'click':
click.append(str(row[2]))
elif row[1] == 'conversion':
conversion.append(str(row[2]))
else:
landing.append(str(row[2]))
xTickMarks.append(str(row[0]))
connection.close()
ax = plt.subplot(111)
w = 0.3
ax.bar(xTickMarks-w, click,width=w,color='b',align='center')
ax.bar(xTickMarks, conversion,width=w,color='g',align='center')
ax.bar(xTickMarks+w, landing,width=w,color='r',align='center')
ax.xaxis_date()
ax.autoscale(tight=True)
plt.show()
当我尝试运行代码时出现以下错误:
TypeError Traceback (most recent call last)
<ipython-input-63-8a9e652a1846> in <module>()
32 ax = plt.subplot(111)
33 w = 0.3
---> 34 ax.bar(xTickMarks-w, click,width=w,color='b',align='center')
35 ax.bar(xTickMarks, conversion,width=w,color='g',align='center')
36 ax.bar(xTickMarks+w, landing,width=w,color='r',align='center')
TypeError: unsupported operand type(s) for -: 'list' and 'float'
尝试将列表转换为numpy数组,不用了。
上述代码的结果数据集是:
01/04/2015 click 0.0036
01/04/2015 conversion 0.0010
01/04/2015 landing 0.0058
02/04/2015 click 0.0132
02/04/2015 conversion 0.0014
02/04/2015 landing 0.0104
参考问题Question
答案 0 :(得分:1)
如果strings
中有xTickMarks
,我认为你想要这样做
ax.bar([float(x)-w for x in xTickMarks], ...)
如果xTickMarks
由浮点数组成,您也可以
ax.bar([x-w for x in xTickMarks], ...)
或
xTickMarks = np.asarray(xTickMarks)
ax.bar(xTickMarks-w, ...)
答案 1 :(得分:1)
xTickMarks
是一个列表。
xTickMarks-w
)时, w = 0.3
会引发异常。
如果您尝试从0.3
的每个元素中减去xTickMarks
,那么您应该使用plonsers方法。
答案 2 :(得分:0)
对于 ax.bar(xTickMarks-w,单击,宽度= w,颜色='b',align ='居中') 这个工作。
您可以尝试这样:
index = np.arrange(len(xTickMarks))
ax = plt.subplot(111)
plt.xticks(index, xTickMarks, fontsize = 9)
w = 0.3
ax.bar(index-w, click,width=w,color='b',align='center')
ax.bar(index, conversion,width=w,color='g',align='center')
ax.bar(index+w, landing,width=w,color='r',align='center')\
这应该有效。