Python数据可视化_课后习题答案 第1章 数据可视化与matplotlib 填空题 视觉空间 表格 箱线图 2D Anaconda 判断题 错误 错误 错误 错误 选择题 C D D D ABCD 简答题 数据可视化是将数据以图形、图像、表格、动画等视觉形式展现的过程,旨在帮助人们更好地理解和分析数据。 柱形图:用于展示不同类别数据的数量对比,清晰直观。 折线图:用于展示数据随时间或其他连续变量的变化趋势。 饼图:用于展示各部分在总体中的比例分布。 pyplot API:面向函数,通过一系列函数调用来绘制图表,简单易用。 object-oriented API:面向对象,通过创建图表对象、轴对象等来进行更细粒度的控制。 编程题 python Copy Code import numpy as np import matplotlib.pyplot as plt # 面向对象方式 fig, ax = plt.subplots() x = np.linspace(0, 2 * np.pi, 100) ax.plot(x, np.sin(x), label='sin(x)') ax.plot(x, np.cos(x), label='cos(x)') ax.legend() plt.show() # 面向函数方式 x = np.linspace(0, 2 * np.pi, 100) plt.plot(x, np.sin(x), label='sin(x)') plt.plot(x, np.cos(x), label='cos(x)') plt.legend() plt.show() 第2章 使用matplotlib绘制简单图表 填空题 Line2D 堆积图 10 判断题 错误 正确 错误 选择题 D C A C C 编程题 python import matplotlib.pyplot as plt plt.rcParams['font.family'] = 'SimHei' # 替换为你选择的字体 import numpy as np # 数据 subjects = ['语文', '数学', '英语', '物理', '化学', '生物'] boys_scores = [85.5, 91, 72, 59, 66, 55] girls_scores = [94, 82, 89.5, 62, 49, 53] # 绘制柱形图 fig, ax1 = plt.subplots() width = 0.35 # 柱形的宽度 x = np.arange(len(subjects)) # x轴的位置 # 绘制两组柱形 boys_bars = ax1.bar(x - width/2, boys_scores, width, label='男生') girls_bars = ax1.bar(x + width/2, girls_scores, width, label='女生') # 设置y轴标签 ax1.set_ylabel('平均成绩(分)') # 设置x轴刻度标签位于两组柱形中间 ax1.set_xticks(x) ax1.set_xticklabels(subjects) # 添加标题 ax1.set_title('高二男生、女生的平均成绩') # 添加图例 ax1.legend() # 向每个柱形的顶部添加注释文本 def autolabel(bars): for bar in bars: height = bar.get_height() ax1.annotate('{}'.format(height), xy=(bar.get_x() + bar.get_width() / 2, height), xytext=(0, 3), # 3 points vertical offset textcoords="offset points", ha='center', va='bottom') autolabel(boys_bars) autolabel(girls_bars) # 显示图形 plt.show() # 绘制堆积柱形图 fig, ax2 = plt.subplots() # 绘制堆积柱形图 boys_girls_scores = [list(a) for a in zip(boys_scores, girls_scores)] stacked_bars = ax2.bar(x, boys_girls_scores, width, label=['男生', '女生'], tick_label=subjects, stacked=True) # 设置y轴标签 ax2.set_ylabel('平均成绩(分)') # 添加标题 ax2.set_title('高二男生、女生的平均成绩(堆积柱形图)') # 向每个堆积柱形的顶部添加注释文本(需要计算总和) def autolabel_stacked(bars): for bar in bars: total_height = sum([rect.get_height() for rect in bar]) ax2.annotate('{}'.format(total_height), xy=(bar.get_x() + bar.get_width() / 2, total_height), xytext=(0, 3), # 3 points vertical offset textcoords="offset points", ha='center', va='bottom') # 由于堆积柱形图返回的是每个柱形的矩形组,我们需要遍历每个组 for bar_group in stacked_bars: autolabel_stacked([bar_group]) # 注意这里传递的是[bar_group],因为autolabel_stacked期望一个列表 # 这里我们不能直接使用ax2.legend()因为legend会为每个堆叠的部分都创建一个图例项,我们需要手动创建 legend_handles = [] for i, label in enumerate(['男生', '女生']): patch = plt.Rectangle((0, 0), 1, 1, fc=plt.cm.Paired(i / 2), label=label) # 使用Paired颜色映射 legend_handles.append(patch) ax2.legend(handles=legend_handles, loc='upper left') # 手动设置图例位置和句柄 # 由于堆积柱形图的x轴标签已经通过tick_label设置,这里不需要再次设置xticks和xticklabels # 显示图形 plt.show() 第3章 图表辅助元素的定制 填空题 数据图形 数据分类或分组 箭头 参考线 数学公式 判断题 错误 正确 错误 错误 正确 选择题 B C B D 简答题 指向型注释文本通过箭头指向特定数据点,而无指向型注释文本则直接放置在数据点附近。 常用的辅助元素包括标题、图例、参考线、注释文本、网格线等。标题帮助理解图表内容;图例解释各组数据的含义;参考线用于比较数据;注释文本提供额外信息;网格线辅助阅读。 第4章 图表样式的美化 填空题 rcParams 颜色 标记 Text style.use() 判断题 错误 正确 正确 正确 错误 选择题 A B D C D 简答题 局部修改只影响当前图表,而全局修改会影响后续创建的所有图表。 fill()用于填充多边形;fill_between()和fill_betweenx()用于填充两条曲线之间的区域,但前者在y轴方向填充,后者在x轴方向填充。 第5章 子图的绘制及坐标轴共享 填空题 分割 sharex 布局管理器 GridSpec 判断题 正确 错误 正确 正确 错误 选择题 D 'col' C wspace 编程题 subplot()用于添加单个子图,subplots()用于一次性创建多个子图并返回一个包含子图的数组,subplot2grid()则允许更灵活地指定子图的位置和大小。 约束布局是一种自动调整子图和图表元素位置以避免重叠的功能。 python Copy Code import numpy as np import matplotlib.pyplot as plt # 绘制子图 fig = plt.figure() ax1 = fig.add_subplot(233) ax1.plot(np.linspace(0, 2*np.pi, 100), np.sin(np.linspace(0, 2*np.pi, 100))) ax2 = fig.add_subplot(236) ax2.plot(np.linspace(0, 2*np.pi, 100), np.cos(np.linspace(0, 2*np.pi, 100))) fig.subplots_adjust(wspace=0, hspace=0) plt.show() # 自定义布局 fig = plt.figure() gs = fig.add_gridspec(2, 3) ax1 = fig.add_subplot(gs0, 1]) ax1.plot(np.linspace(0, 2*np.pi, 100), np.sin(np.linspace(0, 2*np.pi, 100))) ax2 = fig.add_subplot(gs1, 2]) ax2.plot(np.linspace(0, 2*np.pi, 100), np.cos(np.linspace(0, 2*np.pi, 100))) plt.show() 第6章 坐标轴的定制 填空题 主刻度线 轴 spines 判断题 正确 错误 错误 选择题 C C A B D 简答题 刻度定位器用于确定刻度的位置,而格式器则用于定义刻度的显示格式。 编程题 python Copy Code import numpy as np import matplotlib.pyplot as plt import matplotlib.ticker as ticker # 数据 weeks = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] prices = 44.98, 45.02, 44.32, 41.05, 42.08] # 绘制折线图 fig, ax = plt.subplots() ax.plot(weeks, prices, marker='^', linestyle='--', color='#8B0000', linewidth=1.5) # 设置绘图区域位置 ax.set_position(0.2, 0.2, 0.5, 0.5]) # 设置刻度标签和样式 ax.set_xticks(np.arange(len(weeks))) ax.set_xticklabels(weeks) ax.tick_params(direction='in', width=2) # 隐藏轴脊 ax.spines['top'].set_color('none') ax.spines['right'].set_color('none') plt.show() 第7章 绘制3D图表和统计地图 填空题 3D图表 函数 Cylindrical Equal Area Basemap 判断题 错误 正确 正确 选择题 B C A B 简答题 FuncAnimation通过重复调用一个函数来更新图表,而ArtistAnimation则是基于一组Artist对象来制作动画。 Basemap的基本用法包括创建Basemap对象、指定地图投影类型和区域、绘制地图元素(如海岸线、纬度线、经度线等)。 编程题 python Copy Code import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation # 创建图形和轴 fig, ax = plt.subplots() ax.set_xlim(0, 2 * np.pi) ax.set_ylim(-1.5, 1.5) # 绘制正弦曲线 line, = ax.plot([], [], lw=2) # 初始化函数 def init(): line.set_data([], []) return line, # 更新函数 def update(frame): x = np.linspace(0, 2 * np.pi, 1000) y = np.sin(x + frame * 0.05) line.set_data(x, y) dot, = ax.plot(frame * 0.05, np.sin(frame * 0.05), 'ro') ax.text(frame * 0.05, np.sin(frame * 0.05), f'({frame * 0.05:.2f}, {np.sin(frame * 0.05):.2f})', fontsize=10) return line, dot # 创建动画 ani = animation.FuncAnimation(fig, update, frames=np.arange(0, 100), init_func=init, blit=True, interval=20) plt.show() 第8章 使用matplotlib绘制高级图表 填空题 对比关系 树状图 年龄 contour 顶部棉棒 判断题 正确 错误 错误 正确 正确 选择题 C B D C A 简答题 绘制桑基图的流程包括:创建Sankey对象、添加数据(包括流和标签)、设置流的方向和宽度、完成绘制。 编程题 python Copy Code import numpy as np import matplotlib.pyplot as plt from matplotlib.sankey import Sankey # 绘制棉棒图 data = np.array(62253, 51255, 34541, 28733, 17073, 9000, 5963, 2041, 1879, 1681]) labels = np.array(['武磊登上电影频道', '东京奥运会海报', '浓眉哥受伤', '安东尼准绝杀', '湖人单场20记盖帽', '第77届金球奖红毯', '孟非大赞武磊', '李铁上任', '活塞vs湖人', '英超']) fig, ax = plt.subplots() ax.stem(labels, data, basefmt=' ', use_line_collection=True) ax.set_ylabel('搜索指数') for i, d in enumerate(data): ax.text(i, d + 100, f'{d}', ha='center') plt.show() # 绘制桑基图 flows = 62253, -2000, -5000, -4000, -1000, -500, 20000, 500, -200] labels = ['起点', '旅行', '深造', '生活', '购物', '聚餐', '收入', '人情往来', '其它', '终点'] fig, ax = plt.subplots() sankey = Sankey(ax=ax, unit=None) sankey.add(flows=flows, labels=labels, orientations=-1, 1, 1, 1, 1, 1, -1, 1, 1]) diagram = sankey.finish() diagram.text(fontsize=12, fontweight='bold') plt.show() 第9章 可视化后起之秀——pyecharts 填空题 Echarts 对象 嵌入 选项卡 ThemeType 判断题 正确 错误 错误 正确 正确 选择题 C D C B D 简答题 pyecharts的优势包括:支持丰富的图表类型、支持链式调用简化代码、支持自定义主题、易于与Web框架整合等。 pyecharts绘制图表的基本流程包括:导入必要的模块、创建图表对象、添加数据系列、配置图表选项(如标题、坐标轴等)、渲染图表。 编程题 python Copy Code from pyecharts.charts import Bar from pyecharts import options as opts # 绘制柱形图 data = ('2009', 3095), ('2010', 4245), ('2011', 6673), ('2012', 10701), ('2013', 13642), ('2014', 31368), ('2015', 40949), ('2016', 41776), ('2017', 56213), ('2018', 64143) ] bar = Bar(init_opts=opts.InitOpts(theme='ROMANTIC')) bar.add_xaxis(x0] for x in data]) bar.add_yaxis('注册人数', x1] for x in data]) bar.set_global_opts(title_opts=opts.TitleOpts(title='虎扑社区用户注册时间分布')) bar.render('user_registration.html') # 绘制象形柱形图 male_ratio = 4.5 female_ratio = 95.4 total_ratio = male_ratio + female_ratio data_pairs = ('男用户', male_ratio / total_ratio), ('女用户', female_ratio / total_ratio) ] bar = Bar(init_opts=opts.InitOpts(theme='ROMANTIC')) bar.add_xaxis(x0] for x in data_pairs]) bar.add_yaxis('', x1] for x in data_pairs], itemstyle_opts={'border_color': '#fff', 'border_width': 1}) bar.set_global_opts(title_opts=opts.TitleOpts(title='虎扑社区男女用户比例')) bar.set_series_opts(label_opts=opts.LabelOpts(formatter='{c}%')) bar.render('gender_ratio.html')