在matplotlib中设置每个条的位置

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

Set place of each bar in matplotlib

问题

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

# 创建数据集
data = {'C': 20, 'C++': 15, 'Java': 30, 'Python': 35}
courses = list(data.keys())
values = list(data.values())

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

# 创建条形图
plt.bar(courses, values, color='maroon', width=0.4)

plt.xlabel("开设的课程")
plt.ylabel("注册学生人数")
plt.title("不同课程中的注册学生")
plt.show()

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

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

在matplotlib中设置每个条的位置

英文:

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

# creating the dataset
data = {'C':20, 'C++':15, 'Java':30,
        'Python':35}
courses = list(data.keys())
values = list(data.values())
  
fig = plt.figure(figsize = (10, 5))
 
# creating the bar plot
plt.bar(courses, values, color ='maroon',
        width = 0.4)
 
plt.xlabel("Courses offered")
plt.ylabel("No. of students enrolled")
plt.title("Students enrolled in different courses")
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() 对齐刻度和标签。希望这符合你的需求...

# 创建数据集 - 使用数据框并添加距离零点的位置列
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))
# 创建条形图
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")

## 将xlim设置为0到最大值加0.5,以显示所有条形图
plt.xlim(0, df.pos.max() + 0.5)

## 访问每个条形图并根据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是因为你设置了width=0.4

## 调整刻度和刻度标签
plt.xticks(ticks=df.pos, labels=df.courses)
plt.show()

在matplotlib中设置每个条的位置


<details>
<summary>英文:</summary>

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.

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()


[![enter image description here][1]][1]


  [1]: https://i.stack.imgur.com/DJIfE.png

</details>



# 答案2
**得分**: 1

Maybe you just need to *re-order* the keys of your dictionary ?

d = {k: data[k] for k in ["Java", "C++", "Python", "C"]} # <-- 重新排序的`data`
P = [3, 5, 8, 13] # <-- 每个柱状条/刻度的位置
W = 1.5 # <-- 柱状条的宽度

plt.figure(figsize=(7, 4))

plt.bar(P, d.values(), color="maroon", width=W)

plt.xticks(P, d.keys())
plt.xlim(0, max(P) + W)

输出 :

[![点击这里查看图像描述][1]][1]

  [1]: https://i.stack.imgur.com/RTryc.png

<details>
<summary>英文:</summary>

Maybe you just need to *re-order* the keys of your dictionnary ?

    d = {k: data[k] for k in [&quot;Java&quot;, &quot;C++&quot;, &quot;Python&quot;, &quot;C&quot;]} # &lt;-- re-ordered `data`
    P = [3, 5, 8, 13] # &lt;-- positions of each bar/x-tick
    W = 1.5 # &lt;-- width of the bars
    
    plt.figure(figsize=(7, 4))
    
    plt.bar(P, d.values(), color=&quot;maroon&quot;, width=W)
    
    plt.xticks(P, d.keys())
    plt.xlim(0, max(P) + W)

Output :

[![enter image description here][1]][1]


  [1]: https://i.stack.imgur.com/RTryc.png

</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:

确定