这是工作代码.它会创建特定长度的条形图.

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

enter image description here

但我需要更多的 Select .在future ,我将创建这些栏的动画.他们会左右移动.所以我想设置横杆在x轴上的位置. 我该怎么做呢?

我想要的结果是这样的(当我自己设置位置时)

enter image description here

推荐答案

要实现您想要的操作--将每个条形图设置在x轴上的特定位置,您需要 for each 条形图使用set_x().你可以用container.get_children()得到它,然后移动它.

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

# 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

Python相关问答推荐

计算所有前面行(当前行)中列的值

Polars LazyFrame在收集后未返回指定的模式顺序

将特定列信息移动到当前行下的新行

Pandas 都是(),但有一个门槛

运输问题分支定界法&

将tdqm与cx.Oracle查询集成

有没有一种方法可以从python的pussompy比较结果中提取文本?

如何使用Python以编程方式判断和检索Angular网站的动态内容?

利用Selenium和Beautiful Soup实现Web抓取JavaScript表

移动条情节旁边的半小提琴情节在海运

删除marplotlib条形图上的底边

Python脚本使用蓝牙运行在Windows 11与raspberry pi4

Maya Python脚本将纹理应用于所有对象,而不是选定对象

关于两个表达式的区别

计算空值

并行编程:同步进程

将一个双框爆炸到另一个双框的范围内

如何将返回引用的函数与pybind11绑定?

在我融化极点数据帧之后,我如何在不添加索引的情况下将其旋转回其原始形式?

python的文件. truncate()意外地没有截断'