我的代码:#类型和数值信息 x_data = list(category['Category']) y_data = list(category['每百克碳水化合物(克)']) # 绘制折线图 plt.plot(x_data, y_data) # 显示数值 for i, j in zip(x_data, y_data): plt.text(i+1, j-0.1, str(j)) # 设置图表标题和坐标轴标签 plt.title("折线图") plt.xlabel("X 轴") plt.ylabel("Y 轴") # 显示图表 plt.show(),报错:TypeError: can only concatenate str (not "int") to str
时间: 2023-11-30 13:02:34 浏览: 27
这个错误是因为 `i` 是字符串类型,不能直接和整数相加。你需要将 `i` 转换成整数类型,然后再加上一个整数,最后再转换成字符串类型,才能和其他字符串拼接。修改代码如下:
``` python
#类型和数值信息
x_data = list(category['Category'])
y_data = list(category['每百克碳水化合物(克)'])
# 绘制折线图
plt.plot(x_data, y_data)
# 显示数值
for i, j in zip(x_data, y_data):
plt.text(int(i)+1, j-0.1, str(j))
# 设置图表标题和坐标轴标签
plt.title("折线图")
plt.xlabel("X 轴")
plt.ylabel("Y 轴")
# 显示图表
plt.show()
```
这样就可以正常运行了。
相关问题
我的代码:# 类型和其对应数值 x_data = list(category['Category']) y_data = list(category['每百克钠(毫克)']) #颜色集 color_map=['red','cyan','green','pink','yellow','orange','purple','gray'] # 绘制圆环图 fig, ax = plt.subplots() ax.pie(y_data, x_data, color_map, startangle=90) ax.axis('equal') plt.title('Circle Plot') # 添加内部圆环 inner_circle = plt.Circle((0, 0), 0.70, fc='white') fig.gca().add_artist(inner_circle) plt.show(),报错:TypeError: can't multiply sequence by non-int of type 'float'
这个错误是因为在使用 `ax.pie()` 函数时,第二个参数应该是一个数值类型的列表,而你传入了一个字符串类型的列表 `x_data`。你可以将 `x_data` 列表中的字符串转换为数值类型,例如使用 `map()` 函数进行转换:
```python
x_data = list(map(float, category['Category']))
y_data = list(category['每百克钠(毫克)'])
```
另外,`ax.pie()` 函数中的 `colors` 参数应该是一个颜色列表,而你使用了 `color_map` 列表。你需要修改为以下代码:
```python
colors = ['red', 'cyan', 'green', 'pink', 'yellow', 'orange', 'purple', 'gray']
ax.pie(y_data, colors=colors, labels=x_data, startangle=90)
```
完整的代码如下:
```python
import matplotlib.pyplot as plt
import pandas as pd
category = pd.read_csv('category.csv')
x_data = list(map(float, category['Category']))
y_data = list(category['每百克钠(毫克)'])
colors = ['red', 'cyan', 'green', 'pink', 'yellow', 'orange', 'purple', 'gray']
fig, ax = plt.subplots()
ax.pie(y_data, colors=colors, labels=x_data, startangle=90)
ax.axis('equal')
plt.title('Circle Plot')
inner_circle = plt.Circle((0, 0), 0.70, fc='white')
fig.gca().add_artist(inner_circle)
plt.show()
```
将 for index, adcode_dict in enumerate(adcode_list, 1): # 获取adcode 用于拼接完整的url adcode = adcode_dict["adcode"] # 拼接完整的url full_url = base_url + adcode # 发送请求获取天气json数据 response = requests.get(full_url) json_data = response.json() # 第一种方式 # msg = json_data.get("data").get("message") # if msg == "Successful.": # # 获取天气信息 # weather_name = json_data.get("data").get("data")[0].get("live").get("weather_name") # # print(weather_name) # # # 将天气信息 加入到adcode_dict中 # adcode_dict["weather_name"] = weather_name # print(c, adcode_dict) # else: # print(msg) # 第二种方式 try: # 获取天气信息 weather_name = json_data.get("data").get("data")[0].get("live").get("weather_name") # 将天气信息加入到adcode_dict中 adcode_dict["weather_name"] = weather_name if weather_name == '晴': sunny += 1 elif weather_name == '多云': cloud += 1 elif weather_name == '阴': being_cloud += 1 elif '雨' in weather_name: rain += 1 else: haze += 1 print(index, adcode_dict) except Exception as e: print(e)变成一个生成器函数
可以将上述代码改写成生成器函数,每次yield返回一个包含天气信息的adcode_dict字典,例如:
```python
import requests
def get_weather_info(adcode_list):
base_url = "http://www.weather.com.cn/data/cityinfo/"
sunny = cloud = being_cloud = rain = haze = 0
for index, adcode_dict in enumerate(adcode_list, 1):
adcode = adcode_dict["adcode"]
full_url = base_url + adcode
response = requests.get(full_url)
json_data = response.json()
try:
weather_name = json_data.get("weatherinfo").get("weather")
adcode_dict["weather_name"] = weather_name
yield adcode_dict
if weather_name == '晴':
sunny += 1
elif weather_name == '多云':
cloud += 1
elif weather_name == '阴':
being_cloud += 1
elif '雨' in weather_name:
rain += 1
else:
haze += 1
except Exception as e:
print(e)
print("晴天数量:", sunny)
print("多云数量:", cloud)
print("阴天数量:", being_cloud)
print("雨天数量:", rain)
print("雾霾天数量:", haze)
```
调用该生成器函数可以使用for循环来遍历生成器对象,例如:
```python
adcode_list = [{"adcode": "101010100", "city": "北京"},
{"adcode": "101020100", "city": "上海"},
{"adcode": "101280101", "city": "广州"},
{"adcode": "101280601", "city": "深圳"}]
for adcode_dict in get_weather_info(adcode_list):
print(adcode_dict)
```
这将输出每个城市对应的天气信息,并统计不同天气类型的数量。