import pandas as pd
from matplotlib import pyplot as plt
from matplotlib.ticker import FuncFormatter
# 数据
df = pd.read_csv('city_economy.csv')
city_label = '城市'
years_label = '年份'
# 第一个图
beijing = df[df[city_label] == '北京']
plt.rcParams['font.sans-serif'] = ['SimHei']
gdp_label = '地区生产总值(当年价格)(亿元)'
x = beijing[years_label]
y = beijing[gdp_label]
plt.figure(figsize=(14, 6))
plt.plot(x, y, 'ro-')
for i, j in zip(x, y):
plt.annotate(str(j), xy=(i, j), xytext=(-10, 6), textcoords='offset points', fontsize=6)
plt.title('北京市地区生产总值的逐年变化')
plt.xlabel(years_label)
plt.ylabel(gdp_label)
plt.show()
# 第二个图
plt.figure(figsize=(14, 6))
gdp_2020 = df[df[years_label].str.contains("2020")][[city_label, gdp_label]]
df_sorted = gdp_2020.sort_values(by=gdp_label, ascending=False)
bar_colors = ['blue', 'red', 'green', 'yellow', 'cyan', 'purple', 'orange', 'black']
plt.bar(df_sorted[city_label], df_sorted[gdp_label], color=bar_colors)
for i, value in enumerate(df_sorted[gdp_label]):
plt.text(i, value, str(value), ha='center', va='bottom', fontsize=6)
plt.xticks(rotation=45)
plt.title('2020年中国主要城市的地区生成总值对比')
plt.xlabel(years_label)
plt.ylabel(gdp_label)
plt.grid()
plt.tight_layout()
plt.show()
# 第三个图
df_2019 = df[df[years_label].str.contains("2019")]
one_up = df_2019['第一产业增加值(亿元)'] / df_2019[gdp_label] * 100
two_up = df_2019['第二产业增加值(亿元)'] / df_2019[gdp_label] * 100
three_up = df_2019['第三产业增加值(亿元)'] / df_2019[gdp_label] * 100
fig, ax = plt.subplots(figsize=(14, 6))
x = range(len(df_2019[city_label]))
width = 0.2
ax.bar(x, one_up, width=width, color='blue', label='第一产业占比', zorder=3)
ax.bar([i + width for i in x], two_up, width=width, color='red', label='第二产业占比', zorder=2)
ax.bar([i + 2 * width for i in x], three_up, width=width, color='green', label='第三产业占比', zorder=1)
plt.xticks([i + width for i in x], df_2019[city_label], rotation=45)
plt.title('2019年中国主要城市的产业类型分布')
plt.xlabel(city_label)
plt.ylabel('产业比值')
def percent_formatter(num, pos):
return "{:.0f}%".format(num)
formatter = FuncFormatter(percent_formatter)
ax.yaxis.set_major_formatter(formatter)
plt.legend()
plt.grid()
plt.tight_layout()
plt.show()