python - 我们可以在给出约束的同时按升序更改 x 轴吗
问题描述
我绘制了一个条形图,我想在其中按降序显示标签,而我的标签-'五个'应该总是在最后。
上面显示的是我使用下面的代码生成的原始图表。
import matplotlib.pyplot as plt
# x-coordinates of left sides of bars
left = [1, 2, 3, 4, 5]
# heights of bars
height = [10, 24, 36, 40, 5]
# labels for bars
tick_label = ['one', 'two', 'three', 'four', 'five']
# plotting a bar chart
plt.bar(left, height, tick_label = tick_label,
width = 0.8, color = ['red', 'green'])
# naming the x-axis
plt.xlabel('x - axis')
# naming the y-axis
plt.ylabel('y - axis')
# plot title
plt.title('My bar chart!')
# function to show
# function to show the plot
plt.show
输出:
我希望显示 x 轴,descending order from one to four
并且我的fifth label
应该始终位于最后。()
解决方案
IIUC,您只需按降序绘制列表的元素(最后一个除外)。这可以通过对列表的最后一个元素以外的所有元素进行排序,然后将最后一个元素附加到反向排序的列表中来完成。反向排序(降序)可以通过首先对列表进行排序,然后使用[::-1]
. 如果这不是您想要的,请在下面发表评论
import matplotlib.pyplot as plt
left = [1, 2, 3, 4, 5]
height = [10, 24, 36, 40, 5]
tick_label = ['one', 'two', 'three', 'four', 'five']
height_plot = sorted(height[:-1])[::-1] + height[-1:]
plt.bar(left, height_plot, tick_label = tick_label,
width = 0.8, color = ['red', 'green'])
plt.xlabel('x - axis')
plt.ylabel('y - axis')
plt.title('My bar chart!')
plt.show()
如果您还想更改 x 轴刻度标签,请执行以下操作
height_plot = sorted(height[:-1])[::-1] + height[-1:]
new_labels = tick_label[:-1][::-1] + tick_label[-1:]
plt.bar(left, height_plot, tick_label = new_labels,
width = 0.8, color = ['red', 'green'])
推荐阅读
- docker - 无法连接到 Docker 端点 - Swarm Rancher 和 Portainer
- sql - 在 PostgreSQL 中计算累计每日总和
- python - 跨多个设备的 pytest 并行测试
- r - 在 rmarkdown 呈现文档之前是否调用了一个钩子
- html - 响应式设计不适用于 Iphone
- r - 分类变量的“tt”函数中出现意外符号
- starcluster - 您好,我正在 Windows 中安装 Starcluster,但无法完成安装
- c++ - 如何将 numoy ndarray 从 Python 返回到 C++(嵌入)
- powershell - PowerShell : Set-Content Replace word 和 Encoding UTF8 without BOM
- java - 来自可选对象的实体 (Java 8)