【问题标题】:How to display the first bar in the bar plot如何在条形图中显示第一个条形
【发布时间】:2021-12-16 22:24:30
【问题描述】:
  • 从下图中可以看出,第一个条不显示。
  • 为什么不显示以及如何修复代码以使栏显示?
import json 
import requests
import matplotlib.pyplot as plt 

i = 0
while i<=2:
    
    key = '4ee91801f78b4271a5d90623210211'
    main_url = 'http://api.weatherapi.com/v1/current.json'
    city = input('Hangi Şehri Almak istiyorsunuz : ')
    
    response = requests.get(main_url, params = {
        'key': key,
        'q': city,
        'lang' : 'tr'
     })
    
    data = response.json()

    c_values = data['current']['temp_c']
        

    if i == 0:
        city1 = city
        c_values1 = c_values
    elif i == 1:
        city2 = city
        c_values2 = c_values 
    else: 
        city3 = city 
        c_values3 = c_values
    
    i = i + 1 

names = [f'{city1}',f'{city2}',f'{city3}']
values = [f'{c_values1}', f'{c_values2}', f'{c_values3}'] 

plt.bar(names,values)
plt.show()

【问题讨论】:

  • 希望答案是有帮助的。彻底回答问题很耗时。如果您的问题已解决,请接受解决方案 位于答案左上角的 ▲/▼ 箭头下方。如果出现更好的解决方案,则可以接受新的解决方案。如果您的声望超过 15,您还可以使用 ▲/▼ 箭头对答案的有用性进行投票。 如果解决方案无法回答问题,请发表评论。 What should I do when someone answers my question?。谢谢。

标签: python matplotlib bar-chart


【解决方案1】:
  • 问题是[f'{c_values1}', f'{c_values2}', f'{c_values3}']liststr 类型,而不是数字。
    • 应该是[c_values1, c_values2, c_values3],这样可以用数字而不是文本正确地绘制 y 轴。
    • 注意条形图的底部值是'12',它是'Paris' 的顶部
    • ['12.0', '11.0', '17.0'] 注意这些值是字符串。
  • 我建议使用while i&lt;3: 而不是while i&lt;=2
  • 或者,简化代码
i = 0
cd = dict()  # create an empty dict
while i<3:
    
    key = '4ee91801f78b4271a5d90623210211'
    main_url = 'http://api.weatherapi.com/v1/current.json'
    city = input('Hangi Şehri Almak istiyorsunuz : ')
    
    response = requests.get(main_url, params = {
        'key': key,
        'q': city,
        'lang' : 'tr'
     })
    
    data = response.json()

    cd[city] = data['current']['temp_c']  # add the city and temp to the dict
    i+=1

plt.bar(cd.keys(), cd.values())
plt.show()

【讨论】:

    猜你喜欢
    • 2017-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-02
    • 1970-01-01
    • 2019-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多