」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 免費專案:使用 ChatGPT 透過 Python 和 Matplotlib 進行繪圖

免費專案:使用 ChatGPT 透過 Python 和 Matplotlib 進行繪圖

發佈於2024-11-04
瀏覽:996

Free Project: Use ChatGPT to Plot with Python and Matplotlib

Want to learn to plot in Python? ChatGPT will help you.

This project asks ChatGPT to teach you how to generate Python code for creating plots and visualizations. Simply provide a brief description of the plot you want to create, and ChatGPT will generate the necessary code using the popular Matplotlib library. This tool allows even users with no programming experience to develop professional-grade plots for their data. Whether you’re a researcher, data scientist, or student, ChatGPT makes it easy to create beautiful and informative plots in Python. (Generated by ChatGPT with minor changes).

The project in JupyterNotebook is available free in Cognitive Class.


1. Let’s ask about our specific area of interest which we want to learn.

Asking :”teach me how to plot in python”
The result:
There are many ways to plot data in Python. Here is a simple example using Matplotlib, a popular data visualization library in Python:

# using the provided by chatGPT to run in the notebook
import matplotlib.pyplot as plt
# Sample data
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
# Create a figure and an axes
fig, ax = plt.subplots()
# Plot the data
ax.plot(x, y)
# Add a title
ax.set_title('My Plot')
# Show the plot
plt.show()

Free Project: Use ChatGPT to Plot with Python and Matplotlib

This will create a simple line plot of the data in x and y. There are many options and customization options available for creating plots in Matplotlib. For example, you can change the appearance of the lines, change the axis labels, add a legend, etc.

Here is some more information on Matplotlib and other plotting libraries in Python:
The Matplotlib documentation: https://matplotlib.org/stable/index.html
A tutorial on Matplotlib: https://matplotlib.org/stable/tutorials/index.html
Seaborn, a data visualization library based on Matplotlib: https://seaborn.pydata.org/
Plotly, a library for creating interactive plots: https://plotly.com/python/

As you can see, ChatGPT provides introductory text and code blocks (with a copy icon for convenience), and concludes the conversation with additional useful information.

2. You can ask follow-up questions

By simply asking “show me more examples of plots in python”. In fact, chatGPT remembers your previous conversations.
The result:
Here are a few more examples of plots that you can create in Python using the Matplotlib library: Scatter plot

import matplotlib.pyplot as plt

# Sample data
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]

# Create a figure and an axes
fig, ax = plt.subplots()

# Plot the data
ax.scatter(x, y)

# Add a title
ax.set_title('My Scatter Plot')

# Show the plot
plt.show()

Free Project: Use ChatGPT to Plot with Python and Matplotlib

Bar plot

import matplotlib.pyplot as plt

# Sample data
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]

# Create a figure and an axes
fig, ax = plt.subplots()

# Plot the data
ax.bar(x, y)

# Add a title
ax.set_title('My Bar Plot')

# Show the plot
plt.show()

Free Project: Use ChatGPT to Plot with Python and Matplotlib

Pie chart

import matplotlib.pyplot as plt

# Sample data
labels = ['Apples', 'Bananas', 'Oranges']
sizes = [30, 45, 25]

# Create a figure and an axes
fig, ax = plt.subplots()

# Plot the data
ax.pie(sizes, labels=labels)

# Add a title
ax.set_title('My Pie Chart')

# Show the plot
plt.show()

Free Project: Use ChatGPT to Plot with Python and Matplotlib

Keep in mind that these are just a few examples, and there are many other types of plots that you can create in Python using Matplotlib. You can find more information and examples in the Matplotlib documentation: https://matplotlib.org/stable/index.html.

Let's plot from a sample dataset

3. Suggest some sample datasets

The intial stage you need to load data. We can ask ChatGPT to suggest some sample datasets by asking “Could you tell me sample dataset for beginners in python?”
The result:
Sure! Here are a few datasets that might be useful for beginners in Python:

Iris dataset: This is a small dataset that contains information about different species of iris flowers, including the sepal and petal length and width. It is often used as a beginner’s dataset for learning machine learning and data analysis techniques. You can load the Iris dataset in Python using the sklearn.datasets module.

Boston Housing dataset: This dataset contains information about housing prices in the Boston area, including the median value of homes, crime rate, and other factors. It is often used as a beginner’s dataset for learning regression techniques. You can load the Boston Housing dataset in Python using the sklearn.datasets module.

MNIST dataset: This is a dataset of handwritten digits, with 60,000 training examples and 10,000 test examples. It is often used as a beginner’s dataset for learning image classification techniques. You can load the MNIST dataset in Python using the keras.datasets module.

From these suggested datasets, we select Iris dataset to continue to work with as a sample.

3.1. Load the iris dataset as a sample to work wit

h

We need a proper sample in tabular format, so we asked “load iris data with table looking format”
The result:

To load the Iris dataset in a table-like format in Python, you can use the Pandas library. Here is an example of how you can load the Iris dataset and display it in a table-like format:

import pandas as pd
from sklearn import datasets

# Load the Iris dataset
iris = datasets.load_iris()

# Create a DataFrame with the features and target values
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['target'] = iris.target

# Display the DataFrame
print(df)
#--> or we can call the dataset to displace it
df

Free Project: Use ChatGPT to Plot with Python and Matplotlib

_This will create a Pandas DataFrame with the features (sepal length, sepal width, petal length, and petal width) of the Iris dataset as columns, and the target values (the species of iris) as an additional column.

You can then use the usual Pandas functions to manipulate and analyze the data in the DataFrame. For example, you can use the head() function to display the first few rows of the DataFrame, or use the describe() function to get summary statistics for the numerical columns._

4. Plot the dataset

Conveniently, we can ask follow-up questions; here we asked “plot it”
The result:

To plot the Iris dataset using Matplotlib, you can use the following code:

# --> Trying of the suggestions from ChatGPT
# --> we removed the redundant lines (e.g. loading libraries and importing data) from the suggestion

# Create a figure and an axes
fig, ax = plt.subplots()

# Plot the data, coloring the points by the target values
scatter = ax.scatter(df['sepal length (cm)'], df['sepal width (cm)'], c=df['target'])

# Add a legend
legend = ax.legend(*scatter.legend_elements(), title='Species')

# Add a title
ax.set_title('Iris dataset')

# Show the plot
plt.show()

Free Project: Use ChatGPT to Plot with Python and Matplotlib

4.1. Plot-specific column

We select and ask to plot a specific column in the dataset. For example, asking “show me the distribution of the column ‘sepal length (cm)”
The result:

To show the distribution of a column in a Pandas DataFrame, you can use the hist() function of the DataFrame. For example, to show the distribution of the ‘sepal length (cm)’ column in the Iris dataset, you can use the following code:

# Create a figure and an axes
fig, ax = plt.subplots()

# Plot the distribution of the 'sepal length (cm)' column
df['sepal length (cm)'].hist(ax=ax)

# Add a title
ax.set_title('Distribution of sepal length')

# Show the plot
plt.show()

Free Project: Use ChatGPT to Plot with Python and Matplotlib

As you may notice, the plot does not have labels. Therefore, we can **ask “redo it with proper axis labels”.
The result:
**

# Create a figure and an axes
fig, ax = plt.subplots()

# Plot the distribution of the 'sepal length (cm)' column
df['sepal length (cm)'].hist(ax=ax)

# Add axis labels
ax.set_xlabel('Sepal length (cm)')
ax.set_ylabel('Frequency')

# Add a title
ax.set_title('Distribution of sepal length')

# Show the plot
plt.show()

Free Project: Use ChatGPT to Plot with Python and Matplotlib

4.2. More complex plot

Another useful plot to show the distribution is using boxplot which enables us to visualize standard deviation and identify outliers.

Here we ask for a boxplot of all the columns showing in the single plot by asking “show me boxplot of distributions of all columns in same plot”.
The result:

To show the distribution of all columns in a Pandas DataFrame as boxplots on the same plot, you can use the boxplot() function of the DataFrame.

For example, to show the distributions of all columns in the Iris dataset as boxplots, you can use the following code:

import matplotlib.pyplot as plt
import pandas as pd
from sklearn import datasets

# Load the Iris dataset
iris = datasets.load_iris()

# Create a DataFrame with the features
df = pd.DataFrame(iris.data, columns=iris.feature_names)

# Add a column with the target values
df['target'] = iris.target

# Create a figure and an axes
fig, ax = plt.subplots()

# Plot the boxplots of all columns
df.boxplot(ax=ax)

# Add a title
ax.set_title('Distributions of all columns')

# Show the plot
plt.show()

Free Project: Use ChatGPT to Plot with Python and Matplotlib

5. Using chatGPT for your own project

ChatGPT is an excellent tool for working on your project. It is important to frame the question in a way that addresses your problem. Keep in mind that dividing your project into smaller blocks and addressing them individually is the key to addressing the project.

To ask a programming question from ChatGPT, you can simply provide a clear and concise description of your problem, along with any relevant code or error messages. You should also specify the programming language and any libraries or frameworks that you are using.

5.1. How to properly formulate a question (aka. prompt) for ChatGPT

So, let's ask ChatGPT what it thinks.

When formulating a prompt for ChatGPT, it’s important to keep a few things in mind in order to get the most out of the model:
Be specific and clear about what you want the model to do. For example, instead of asking “What do you know about this topic?”, ask “Can you provide a brief overview of the history of the topic?”

Provide context if necessary. If you’re asking a question about a specific event or person, give some background information so that the model can understand the context in which you’re asking the question.

Be concise. Long and complex prompts can be difficult for the model to understand and may result in less accurate or relevant responses.

Avoid using overly technical language or jargon that the model may not be familiar with.

Avoid asking multiple questions in one prompt, it is better to ask one question at a time.

Here are a few examples of good prompts for ChatGPT:
“Can you explain the main difference between supervised and unsupervised learning?”

“What are the main components of a neural network and how do they work?”

“Please write a short story about a robot who can read minds”

On the other hand, some examples of poor prompts would be:

“everything”
“What can you tell me?”
“what you know”

By following these guidelines, you can help ensure that you get the most accurate and relevant responses from the model when using ChatGPT.

5.2. Keep in mind as a data scientist

ChatGPT is not perfect; the example provided is from sklearn. In the real world, you need to load your own data from your resource, using Pandas (the example below shows loading iris from local storage).

In general, as a practicing data scientist, you will frequently encounter the multifaceted process of data collection, preparation, model construction, and interpretation. These stages each have their own unique requirements in terms of skills and resources. For instance, you may utilize pandas to load and manipulate your datasets. It’s important to keep in mind that the examples provided by ChatGPT are intended to serve as a foundational learning aid, and may not be suitable for handling more complex or substantial datasets.

5.3. Don’t panic chat GPT is not going to replace data scientist (yet!)

So, let's ask ChatGPT what it thinks.

There are several reasons why ChatGPT and other large language models are not going to replace data scientists:

Data scientists have a much broader skill set: Data scientists are trained in a wide range of skills, including data analysis, machine learning, programming, statistics, and more. ChatGPT and other large language models are only capable of generating text based on a given prompt, and they do not have the other skills that data scientists possess.

Data scientists can interpret and explain the results of their work: Data scientists are trained to interpret and explain the results of their work, which is critical for decision-making and communication with stakeholders. ChatGPT and other large language models are not capable of interpreting or explaining the results of their work.

Data scientists can work with a wide range of data: Data scientists are trained to work with a wide range of data, including structured and unstructured data, and they can use a variety of tools and techniques to extract insights from the data. ChatGPT and other large language models are only capable of generating text based on a given prompt, and they are not able to work with other types of data.

Data scientists can work with a wide range of stakeholders: Data scientists are trained to work with a wide range of stakeholders, including business leaders, subject matter experts, and technical experts, and they can communicate complex concepts in a clear and understandable way. ChatGPT and other large language models are not able to work with stakeholders or communicate complex concepts.

Check out this beginner friendly guided project other free courses developed by IBM developers and data scientists at https://cognitiveclass.ai/

Until next time!

版本聲明 本文轉載於:https://dev.to/cognitiveclass/free-project-use-chatgpt-to-plot-with-python-and-matplotlib-5ha6?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>
  • Bootstrap 4 Beta 中的列偏移發生了什麼事?
    Bootstrap 4 Beta 中的列偏移發生了什麼事?
    Bootstrap 4 Beta:列偏移的刪除和恢復Bootstrap 4 在其Beta 1 版本中引入了重大更改柱子偏移了。然而,隨著 Beta 2 的後續發布,這些變化已經逆轉。 從 offset-md-* 到 ml-auto在 Bootstrap 4 Beta 1 中, offset-md-*...
    程式設計 發佈於2024-11-16
  • 在 Go 中使用 WebSocket 進行即時通信
    在 Go 中使用 WebSocket 進行即時通信
    构建需要实时更新的应用程序(例如聊天应用程序、实时通知或协作工具)需要一种比传统 HTTP 更快、更具交互性的通信方法。这就是 WebSockets 发挥作用的地方!今天,我们将探讨如何在 Go 中使用 WebSocket,以便您可以向应用程序添加实时功能。 在这篇文章中,我们将介绍: WebSoc...
    程式設計 發佈於2024-11-16
  • 大批
    大批
    方法是可以在物件上呼叫的 fns 數組是對象,因此它們在 JS 中也有方法。 slice(begin):將陣列的一部分提取到新數組中,而不改變原始數組。 let arr = ['a','b','c','d','e']; // Usecase: Extract till index ...
    程式設計 發佈於2024-11-16
  • 如何在 PHP 中組合兩個關聯數組,同時保留唯一 ID 並處理重複名稱?
    如何在 PHP 中組合兩個關聯數組,同時保留唯一 ID 並處理重複名稱?
    在 PHP 中組合關聯數組在 PHP 中,將兩個關聯數組組合成一個數組是常見任務。考慮以下請求:問題描述:提供的代碼定義了兩個關聯數組,$array1和$array2。目標是建立一個新陣列 $array3,它合併兩個陣列中的所有鍵值對。 此外,提供的陣列具有唯一的 ID,而名稱可能重疊。要求是建構一...
    程式設計 發佈於2024-11-16
  • 為什麼 Visual Studio 2010 中 x86 和 x64 的浮點運算不同?
    為什麼 Visual Studio 2010 中 x86 和 x64 的浮點運算不同?
    x86 與x64 之間的浮點算術差異在Visual Studio 2010 中,x86 與x64 版本之間的浮點算術存在明顯差異當比較某些表達式的值時出現。這種差異體現在以下程式碼:float a = 50.0f; float b = 65.0f; float c = 1.3f; float d =...
    程式設計 發佈於2024-11-15
  • 如何提高帶有通配符的 MySQL LIKE 運算子的效能?
    如何提高帶有通配符的 MySQL LIKE 運算子的效能?
    MySQL LIKE 運算子最佳化MySQL LIKE 運算子最佳化問題:使用萬用字元(例如'%test% ')?答案: 是的,在查詢中使用特定模式時,MySQL 可以最佳化LIKE 運算子的效能。 前綴通配符: 如果您的查詢類似於 foo LIKE 'abc%' 或...
    程式設計 發佈於2024-11-15
  • 如何使用 PHP 透過 POST 向外部網站發送資料?
    如何使用 PHP 透過 POST 向外部網站發送資料?
    在PHP 中透過POST 重新導向並傳送資料在PHP 中,您可能會遇到需要將使用者重新導向到外部的情況網站並透過POST 將資料傳遞到該網站。與 HTML 表單不同,PHP 本身並不支援此行為。 GET 與POST在Web 開發中,有兩種​​主要方法用於從來源發送資料到目的地: GET:資料作為查詢...
    程式設計 發佈於2024-11-15
  • 如何使用 GCC 捕捉 Linux 中的分段錯誤?
    如何使用 GCC 捕捉 Linux 中的分段錯誤?
    捕獲Linux 中的分段錯誤問:我在第三方庫中遇到分段錯誤,但我無法解決根本問題。是否有跨平台或特定於平台的解決方案來使用 gcc 捕獲 Linux 中的這些錯誤? A:Linux 允許將分段錯誤作為異常處理。當程式遇到此類故障時,它會收到 SIGSEGV 訊號。透過設定訊號處理程序,您可以攔截此訊...
    程式設計 發佈於2024-11-15
  • 如何在不建立實例的情況下存取Go結構體的類型?
    如何在不建立實例的情況下存取Go結構體的類型?
    在不創建物理結構的情況下訪問Reflect.Type在Go 中,動態加載問題的解決方案需要訪問結構的類型,而無需物理創建它們。雖然現有的解決方案要求在類型註冊之前建立結構體並清除零,但有一種更有效的方法。 人們可以利用 reflect.TypeOf((*Struct)(nil)).Elem()手術。...
    程式設計 發佈於2024-11-15
  • Java中如何有效率地將整數轉換為位元組數組?
    Java中如何有效率地將整數轉換為位元組數組?
    Java 中整數到位元組數組的高效轉換將整數轉換為位元組數組可用於多種目的,例如網路傳輸或資料儲存。有多種方法可以實現此轉換。 ByteBuffer 類別:一個有效的方法是使用 ByteBuffer 類別。 ByteBuffer 是一個儲存二進位資料並提供各種操作來操縱它的緩衝區。使用 ByteBu...
    程式設計 發佈於2024-11-15
  • 如何在 Go 中按多個欄位對結構體切片進行排序?
    如何在 Go 中按多個欄位對結構體切片進行排序?
    按多個欄位對切片物件進行排序依多個條件排序考慮以下Parent 和Child 結構:type Parent struct { id string children []Child } type Child struct { id string }假設我們有一個帶有...
    程式設計 發佈於2024-11-15
  • Qt 線程與 Python 線程:我應該在 PyQt 應用程式中使用哪個?
    Qt 線程與 Python 線程:我應該在 PyQt 應用程式中使用哪個?
    PyQt 應用程式中的線程:Qt 線程與Python 線程尋求使用PyQt 創建響應式GUI 應用程式的開發人員經常遇到到執行的挑戰長時間運行的任務而不影響UI 的功能。一種解決方案是使用單獨的執行緒來完成這些任務。這就提出了使用 Qt 執行緒還是原生 Python 執行緒模組的問題。 Qt 執行緒...
    程式設計 發佈於2024-11-15
  • 為什麼我的PHP提交按鈕沒有觸發回顯和表格顯示?
    為什麼我的PHP提交按鈕沒有觸發回顯和表格顯示?
    PHP 提交按鈕困境:不可用的回顯和表格您的程式碼打算在點擊「提交」按鈕時顯示回顯和表格在PHP 表單上。但是,您遇到了這些元素仍然隱藏的問題。這是因為您使用 if(isset($_POST['submit'])) 來控制這些元素的顯示,但提交按鈕缺少 name 屬性。 解決方案:提...
    程式設計 發佈於2024-11-15
  • 為什麼我的 @font-face EOT 字型無法在 Internet Explorer 中透過 HTTPS 載入?
    為什麼我的 @font-face EOT 字型無法在 Internet Explorer 中透過 HTTPS 載入?
    @font-face EOT 無法透過HTTPS 載入:解決方案在Internet 中與@font-face EOT 檔案在Internet 中無法透過HTTPS 載入的問題在Explorer 版本7、8 和9 中,使用者發現無論HTTPS 上包含的HTML 頁面的託管狀態如何,問題仍然存在。經過實...
    程式設計 發佈於2024-11-15
  • 為什麼透過 Makefile 運行 Go 程式時出現「權限被拒絕」錯誤?
    為什麼透過 Makefile 運行 Go 程式時出現「權限被拒絕」錯誤?
    權限被拒絕:調查「go run」和Makefile 呼叫之間的差異透過Makefile 執行Go 程式時遇到權限被拒絕錯誤可能會令人困惑。此問題源自於 GNU make 或其 gnulib 元件中的錯誤。根本原因在於系統 PATH 中存在一個名為「go」的目錄,該目錄位於實際 Go 執行檔所在的目錄...
    程式設計 發佈於2024-11-15

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3