我目前正在制作一个程序,其中一个酒吧是为客户准备的。我希望此栏以不同的颜色来区分。我曾经通过遍历字典(barChartObjects)来做到这一点,当字典的键与参数(公司)匹配时,它将改变颜色。发生这种情况是因为它分别绘制了每个条形图,并且效果很好。由于标签的格式问题,我不得不切换显示图形的方式,现在我对如何使用新功能执行以前的工作感到困惑。
def plotCompany(barChartObjects, company):
# axis of data
x = []
y = []
print("Company: " + company)
# date for the file output name
dateForOutput = date.today()
# append the attributed input to the corresponding axis
for key, value in barChartObjects.items():
x.append(key)
y.append(value)
freq_series = pd.Series.from_array(y)
# Plot the figure.
plt.figure(figsize=(12, 8))
# this is where I set the color for the graph, I am assuming I will need to change something here
ax = freq_series.plot(kind='bar', color= "#36C989")
ax.set_title("Total Shareholder Return (" + (date.today()-timedelta(days=30)).strftime("%b %d %Y") + ")")
ax.set_xlabel("Companies")
ax.set_ylabel("Percent Change")
ax.set_xticklabels(x)
plt.text(-0.25, 12, "Median: " + str(medianCalc(barChartObjects)) + "%")
add_value_labels(ax)
# save the file to my directory.
plotDirectory = config.getDirectory(company)
plt.savefig(plotDirectory, quality = 95)
plt.show()
return plotDirectory
以上是我当前设置功能的方式。作为参考,下面是我以前使用的功能,该功能为它们正确着色但格式古怪,因此我使用了此新功能。
def graphCompany(barChartObjects, company):
# axis of data
x = []
y = []
print("Company: " + company)
# date for the file output name
dateForOutput = date.today()
# append the attributed input to the corresponding axis
for key, value in barChartObjects.items():
x.append(key)
y.append(value)
i = 0
for key, value in barChartObjects.items():
if (key == company):
plt.bar(x[i], y[i],width = calcWidth(barChartObjects), color = "#289EE0")
i = i + 1
else:
plt.bar(x[i], y[i],width = calcWidth(barChartObjects), color = "#36C989")
i = i + 1
# label the bar chart
plt.autoscale(enable=True, axis='both', tight=None)
plt.xlabel("Companies")
plt.ylabel("Percent Change")
plt.title("Total Shareholder Return (" + (date.today()-timedelta(days=30)).strftime("%b %d %Y") + ")")
plt.text(-0.70, 9.25, "Median: " + str(medianCalc(barChartObjects)) + "%")
# add labels to see the specific percent change for each x
for a,b in zip(x, y):
plt.text(a, b, str("%.2f" % b + "%"))
# save the file to my directory.
plotDirectory = config.getDirectory(company)
plt.savefig(plotDirectory, quality = 95)
plt.show()
return plotDirectory
答案 0 :(得分:2)
这两种方法似乎都很复杂。如果我理解正确,则希望根据x轴类别绘制带有颜色的分类条形图。例如:
import matplotlib.pyplot as plt
companies = ["Company A", "Company B", "Company C", "Company D"]
values = [17, 23, 12, 32]
myclient = "Company B"
colors = ["grey" if company is not myclient else "red" for company in companies]
plt.bar(companies, values, color=colors)
plt.show()