我目前正在制作一个程序,其中一个栏是为客户提供的。我希望这个栏用不同的颜色来区分。我曾经通过迭代字典(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
最佳答案
这两种方法看起来都很复杂。如果我理解正确的话,您想要绘制一个分类条形图,其颜色取决于 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()
关于python - 如何区分 matplotlib 条形图中特定的 x 条形颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55528247/