经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » Python » 查看文章
python绘制发散型柱状图+误差阴影时间序列图+双坐标系时间序列图+绘制金字塔图
来源:jb51  时间:2022/8/16 19:28:23  对本文有异议

1.绘制发散型柱状图

python绘制发散型柱状图,展示单个指标的变化的顺序和数量,在柱子上添加了数值文本。

实现代码:

  1. import numpy as np
  2. import pandas as pd
  3. import matplotlib as mpl
  4. import matplotlib.pyplot as plt
  5. import seaborn as sns
  6. import warnings
  7. warnings.filterwarnings(action='once')
  8. df = pd.read_csv("C:\工作\学习\数据杂坛/datasets/mtcars.csv")
  9. x = df.loc[:, ['mpg']]
  10. df['mpg_z'] = (x - x.mean()) / x.std()
  11. df['colors'] = ['red' if x < 0 else 'green' for x in df['mpg_z']]
  12. df.sort_values('mpg_z', inplace=True)
  13. df.reset_index(inplace=True)
  14. # Draw plot
  15. plt.figure(figsize=(10, 6), dpi=80)
  16. plt.hlines(y=df.index,
  17. ? ? ? ? ? ?xmin=0,
  18. ? ? ? ? ? ?xmax=df.mpg_z,
  19. ? ? ? ? ? ?color=df.colors,
  20. ? ? ? ? ? ?alpha=0.8,
  21. ? ? ? ? ? ?linewidth=5)
  22. for x, y, tex in zip(df.mpg_z, df.index, df.mpg_z):
  23. ? ? t = plt.text(x, y, round(tex, 2), horizontalalignment='right' if x < 0 else 'left',
  24.  
  25. ? ? ? ? ? ? ? ? ?verticalalignment='center', fontdict={'color':'black' if x < 0 else 'black', 'size':10})
  26.  
  27. # Decorations
  28.  
  29. plt.gca().set(ylabel='$Model', xlabel='$Mileage')
  30. plt.yticks(df.index, df.cars, fontsize=12)
  31. plt.xticks(fontsize=12)
  32. plt.title('Diverging Bars of Car Mileage')
  33. plt.grid(linestyle='--', alpha=0.5)
  34. plt.show()

实现效果:

2.绘制带误差阴影的时间序列图

实现功能:

python绘制带误差阴影的时间序列图。

实现代码:

  1. from scipy.stats import sem
  2. import pandas as pd
  3. import matplotlib.pyplot as plt
  4. # Import Data
  5. df_raw = pd.read_csv('F:\数据杂坛\datasets\orders_45d.csv',
  6. ? ? ? ? ? ? ? ? ? ? ?parse_dates=['purchase_time', 'purchase_date'])
  7.  
  8. # Prepare Data: Daily Mean and SE Bands
  9. df_mean = df_raw.groupby('purchase_date').quantity.mean()
  10. df_se = df_raw.groupby('purchase_date').quantity.apply(sem).mul(1.96)
  11.  
  12. # Plot
  13. plt.figure(figsize=(10, 6), dpi=80)
  14. plt.ylabel("Daily Orders", fontsize=12)
  15. x = [d.date().strftime('%Y-%m-%d') for d in df_mean.index]
  16. plt.plot(x, df_mean, color="#c72e29", lw=2)
  17. plt.fill_between(x, df_mean - df_se, df_mean + df_se, color="#f8f2e4")
  18.  
  19. # Decorations
  20. # Lighten borders
  21. plt.gca().spines["top"].set_alpha(0)
  22. plt.gca().spines["bottom"].set_alpha(1)
  23. plt.gca().spines["right"].set_alpha(0)
  24. plt.gca().spines["left"].set_alpha(1)
  25. plt.xticks(x[::6], [str(d) for d in x[::6]], fontsize=12)
  26. plt.title("Daily Order Quantity of Brazilian Retail with Error Bands (95% confidence)",fontsize=14)
  27.  
  28. # Axis limits
  29. s, e = plt.gca().get_xlim()
  30. plt.xlim(s, e - 2)
  31. plt.ylim(4, 10)
  32.  
  33. # Draw Horizontal Tick lines
  34. for y in range(5, 10, 1):
  35. ? ? plt.hlines(y,
  36. ? ? ? ? ? ? ? ?xmin=s,
  37. ? ? ? ? ? ? ? ?xmax=e,
  38. ? ? ? ? ? ? ? ?colors='black',
  39. ? ? ? ? ? ? ? ?alpha=0.5,
  40. ? ? ? ? ? ? ? ?linestyles="--",
  41. ? ? ? ? ? ? ? ?lw=0.5)
  42.  
  43. plt.show()

实现效果:

3.绘制双坐标系时间序列图

实现功能:

python绘制双坐标系(双变量)时间序列图。

实现代码:

  1. import pandas as pd
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4.  
  5. # Import Data
  6. df = pd.read_csv("F:\数据杂坛\datasets\economics.csv")
  7.  
  8. x = df['date']
  9. y1 = df['psavert']
  10. y2 = df['unemploy']
  11.  
  12. # Plot Line1 (Left Y Axis)
  13. fig, ax1 = plt.subplots(1, 1, figsize=(12, 6), dpi=100)
  14. ax1.plot(x, y1, color='tab:red')
  15.  
  16. # Plot Line2 (Right Y Axis)
  17. ax2 = ax1.twinx() ?# instantiate a second axes that shares the same x-axis
  18. ax2.plot(x, y2, color='tab:blue')
  19.  
  20. # Decorations
  21. # ax1 (left Y axis)
  22. ax1.set_xlabel('Year', fontsize=18)
  23. ax1.tick_params(axis='x', rotation=70, labelsize=12)
  24. ax1.set_ylabel('Personal Savings Rate', color='#dc2624', fontsize=16)
  25. ax1.tick_params(axis='y', rotation=0, labelcolor='#dc2624')
  26. ax1.grid(alpha=.4)
  27.  
  28. # ax2 (right Y axis)
  29. ax2.set_ylabel("Unemployed (1000's)", color='#01a2d9', fontsize=16)
  30. ax2.tick_params(axis='y', labelcolor='#01a2d9')
  31. ax2.set_xticks(np.arange(0, len(x), 60))
  32. ax2.set_xticklabels(x [::60], rotation=90, fontdict={'fontsize': 10})
  33. ax2.set_title(
  34. ? ? "Personal Savings Rate vs Unemployed: Plotting in Secondary Y Axis",
  35. ? ? fontsize=18)
  36. fig.tight_layout()
  37. plt.show()

实现效果:

4.绘制金字塔图

实现功能:

python绘制金字塔图,一种排过序的分组水平柱状图barplot,可很好展示不同分组之间的差异,可可视化逐级过滤或者漏斗的每个阶段。

实现代码:

  1. import pandas as pd
  2. import matplotlib.pyplot as plt
  3. import seaborn as sns
  4.  
  5. # Read data
  6. df = pd.read_csv("D:\数据杂坛\datasets\email_campaign_funnel.csv")
  7.  
  8. # Draw Plot
  9. plt.figure()
  10. group_col = 'Gender'
  11. order_of_bars = df.Stage.unique()[::-1]
  12. colors = [
  13. ? ? plt.cm.Set1(i / float(len(df[group_col].unique()) - 1))
  14. ? ? for i in range(len(df[group_col].unique()))
  15. ]
  16.  
  17. for c, group in zip(colors, df[group_col].unique()):
  18. ? ? sns.barplot(x='Users',
  19. ? ? ? ? ? ? ? ? y='Stage',
  20. ? ? ? ? ? ? ? ? data=df.loc[df[group_col] == group, :],
  21. ? ? ? ? ? ? ? ? order=order_of_bars,
  22. ? ? ? ? ? ? ? ? color=c,
  23. ? ? ? ? ? ? ? ? label=group)
  24.  
  25. # Decorations
  26. plt.xlabel("$Users$")
  27. plt.ylabel("Stage of Purchase")
  28. plt.yticks(fontsize=12)
  29. plt.title("Population Pyramid of the Marketing Funnel", fontsize=18)
  30. plt.legend()
  31. plt.savefig('C:\工作\学习\数据杂坛\素材\\0815\金字塔', dpi=300, bbox_inches = 'tight')
  32. plt.show()

实现效果:

到此这篇关于python绘制发散型柱状图+误差阴影时间序列图+双坐标系时间序列图+绘制金字塔图的文章就介绍到这了,更多相关Python图绘制内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号