在matplotlib中设置每个条的位置

huangapple go评论93阅读模式
英文:

Set place of each bar in matplotlib

问题

这是可工作的代码。它创建了特定长度的条形图。

  1. # 创建数据集
  2. data = {'C': 20, 'C++': 15, 'Java': 30, 'Python': 35}
  3. courses = list(data.keys())
  4. values = list(data.values())
  5. fig = plt.figure(figsize=(10, 5))
  6. # 创建条形图
  7. plt.bar(courses, values, color='maroon', width=0.4)
  8. plt.xlabel("开设的课程")
  9. plt.ylabel("注册学生人数")
  10. plt.title("不同课程中的注册学生")
  11. plt.show()

但我需要更多选项。将来我将创建这些条形图的动画。它们将左右移动。所以我想要在x轴上设置条的位置。如何做到这一点?

我的期望结果看起来像这样(当我自己设置位置时)。

在matplotlib中设置每个条的位置

英文:

This is working code. It creates bars of specific length.

  1. # creating the dataset
  2. data = {'C':20, 'C++':15, 'Java':30,
  3. 'Python':35}
  4. courses = list(data.keys())
  5. values = list(data.values())
  6. fig = plt.figure(figsize = (10, 5))
  7. # creating the bar plot
  8. plt.bar(courses, values, color ='maroon',
  9. width = 0.4)
  10. plt.xlabel("Courses offered")
  11. plt.ylabel("No. of students enrolled")
  12. plt.title("Students enrolled in different courses")
  13. plt.show()

在matplotlib中设置每个条的位置

But I need more options. In future I will create animation of these bars. They will move left and right. So I want to set place of bar on x axis.
How can I do it?

My desired result looks like this (when I set place by my own)

在matplotlib中设置每个条的位置

答案1

得分: 1

为实现你要的功能 - 在x轴的特定位置设置每个条形图,你需要对每个条形图使用 set_x()。你可以使用 container.get_children() 获取这些条形图,然后将其移动。

请注意,我将数据设为一个数据框,并添加了一个名为 pos 的列。这将定义每个条形图距离x轴零点的距离。绘制条形图,然后使用 set_x() 移动条形图,使用 plt.xlim()plt.xticks() 对齐刻度和标签。希望这符合你的需求...

  1. # 创建数据集 - 使用数据框并添加距离零点的位置列
  2. data = {'courses': ['C', 'C++', 'Java', 'Python'], 'values': [20, 15, 30, 35], 'pos': [2, 3, 5, 7]}
  3. df = pd.DataFrame(data)
  4. fig = plt.figure(figsize=(10, 5))
  5. # 创建条形图
  6. plt.bar(df['courses'], df['values'], color='maroon', width=0.4)
  7. plt.xlabel("Courses offered")
  8. plt.ylabel("No. of students enrolled")
  9. plt.title("Students enrolled in different courses")
  10. ## 将xlim设置为0到最大值加0.5,以显示所有条形图
  11. plt.xlim(0, df.pos.max() + 0.5)
  12. ## 访问每个条形图并根据df.pos中的值设置位置
  13. for container in plt.gca().containers:
  14. for i, child in enumerate(container.get_children()):
  15. child.set_x(df.pos[i] - 0.2) ## 0.2是因为你设置了width=0.4
  16. ## 调整刻度和刻度标签
  17. plt.xticks(ticks=df.pos, labels=df.courses)
  18. plt.show()

在matplotlib中设置每个条的位置

  1. <details>
  2. <summary>英文:</summary>
  3. To do what you are looking for - setting each bar at a specific place in the x-axis, you need to use `set_x()` for each of the bars. You can get this using `container.get_children()` and then move it around.
  4. Note that I have the data as a dataframe and added a column called `pos`. This will define the distance of each bar from x-axis - zero. Plot the bars, then use set_x() to move the bars and `plt.xlim()` and `plt.xticks()` to align the ticks and labels. Hope this is what you are looking for...

creating the dataset - Using dataframe and adding pos column for distance from zero

data = {'courses' : ['C', 'C++', 'Java', 'Python'], 'values' : [20, 15, 30, 35], 'pos' : [2, 3, 5, 7]}
df=pd.DataFrame(data)

fig = plt.figure(figsize = (10, 5))

creating the bar plot

plt.bar(df['courses'], df['values'], color ='maroon', width = 0.4)
plt.xlabel("Courses offered")
plt.ylabel("No. of students enrolled")
plt.title("Students enrolled in different courses")

Set xlim from 0 to largest value plus 0.5 to show all bars

plt.xlim(0, df.pos.max()+0.5)

Access each bar and set the position based on value in df.pos

for container in plt.gca().containers:
for i, child in enumerate(container.get_children()):
child.set_x(df.pos[i]-0.2) ## 0.2 as you set width=0.4

##Adjust ticks and ticklabels
plt.xticks(ticks=df.pos, labels=df.courses)
plt.show()

  1. [![enter image description here][1]][1]
  2. [1]: https://i.stack.imgur.com/DJIfE.png
  3. </details>
  4. # 答案2
  5. **得分**: 1
  6. Maybe you just need to *re-order* the keys of your dictionary ?
  7. d = {k: data[k] for k in ["Java", "C++", "Python", "C"]} # <-- 重新排序的`data`
  8. P = [3, 5, 8, 13] # <-- 每个柱状条/刻度的位置
  9. W = 1.5 # <-- 柱状条的宽度
  10. plt.figure(figsize=(7, 4))
  11. plt.bar(P, d.values(), color="maroon", width=W)
  12. plt.xticks(P, d.keys())
  13. plt.xlim(0, max(P) + W)
  14. 输出 :
  15. [![点击这里查看图像描述][1]][1]
  16. [1]: https://i.stack.imgur.com/RTryc.png
  17. <details>
  18. <summary>英文:</summary>
  19. Maybe you just need to *re-order* the keys of your dictionnary ?
  20. d = {k: data[k] for k in [&quot;Java&quot;, &quot;C++&quot;, &quot;Python&quot;, &quot;C&quot;]} # &lt;-- re-ordered `data`
  21. P = [3, 5, 8, 13] # &lt;-- positions of each bar/x-tick
  22. W = 1.5 # &lt;-- width of the bars
  23. plt.figure(figsize=(7, 4))
  24. plt.bar(P, d.values(), color=&quot;maroon&quot;, width=W)
  25. plt.xticks(P, d.keys())
  26. plt.xlim(0, max(P) + W)
  27. Output :
  28. [![enter image description here][1]][1]
  29. [1]: https://i.stack.imgur.com/RTryc.png
  30. </details>

huangapple
  • 本文由 发表于 2023年5月21日 18:02:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76299315.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定