python可视化分析(一)-绘制散点图

实现功能:

python绘制散点图,展现两个变量间的关系,当数据包含多组时,使用不同颜色和形状区分。

实现代码:

import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings(action='once')
plt.style.use('seaborn-whitegrid')
sns.set_style("whitegrid")
print(mpl.__version__)
print(sns.__version__)

def draw_scatter(file):
    # Import dataset
    midwest = pd.read_csv(file)
    # Prepare Data
    # Create as many colors as there are unique midwest['category']
    categories = np.unique(midwest['category'])
    colors = [plt.cm.Set1(i / float(len(categories) - 1)) for i in range(len(categories))]
    # Draw Plot for Each Category
    plt.figure(figsize=(10, 6), dpi=100, facecolor='w', edgecolor='k')

    for i, category in enumerate(categories):
        plt.scatter('area', 'poptotal', data=midwest.loc[midwest.category == category, :],s=20,c=colors[i],label=str(category))

    # Decorations
    plt.gca().set(xlim=(0.0, 0.1), ylim=(0, 90000),)

    plt.xticks(fontsize=10)
    plt.yticks(fontsize=10)
    plt.xlabel('Area', fontdict={'fontsize': 10})
    plt.ylabel('Population', fontdict={'fontsize': 10})
    plt.title("Scatterplot of Midwest Area vs Population", fontsize=12)
    plt.legend(fontsize=10)
    plt.show()

draw_scatter("F:\数据杂坛\datasets\midwest_filter.csv")

实现效果:

 

喜欢记得点赞,在看,收藏,

关注V订阅号:数据杂坛,获取数据集,完整代码和效果,将持续更新!

 

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,下面给出一个简单的示例代码,使用Matplotlib库实现交互式绘制散点图和折线图: ```python import matplotlib.pyplot as plt import numpy as np # 生成样本数据 x = np.linspace(0, 10, 100) y = np.sin(x) # 创建图形窗口和子图 fig, ax = plt.subplots() # 绘制散点图 scatter = ax.scatter(x, y, c=x, cmap='coolwarm') ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_title('Scatter Plot') # 添加交互式功能 annot = ax.annotate("", xy=(0,0), xytext=(20,20), textcoords="offset points", bbox=dict(boxstyle="round", fc="w"), arrowprops=dict(arrowstyle="->")) annot.set_visible(False) def update_annot(ind): pos = scatter.get_offsets()[ind["ind"][0]] annot.xy = pos text = f"x={pos[0]:.2f}, y={pos[1]:.2f}" annot.set_text(text) def hover(event): vis = annot.get_visible() if event.inaxes == ax: cont, ind = scatter.contains(event) if cont: update_annot(ind) annot.set_visible(True) fig.canvas.draw_idle() else: if vis: annot.set_visible(False) fig.canvas.draw_idle() # 绑定图形交互事件 fig.canvas.mpl_connect("motion_notify_event", hover) # 绘制折线图 fig, ax = plt.subplots() ax.plot(x, y) ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_title('Line Plot') # 显示图形 plt.show() ``` 运行上述代码后,会生成两个图形窗口,一个是散点图,一个是折线图。在散点图中,当鼠标移动到某个点上时,会显示该点的坐标信息;在折线图中,没有添加交互式功能。 对于所绘制的图形进行分析,可以根据具体需求进行,例如: - 散点图中,可以分析数据的分布情况、异常值等; - 折线图中,可以分析数据的趋势、周期性等。 由于这只是一个简单的示例,具体分析需要结合具体数据和业务场景进行。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

数据杂坛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值