Spaces:
Build error
Build error
File size: 12,438 Bytes
3d5190c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 |
Create a streamlit python program that renders a plotly graph object treemap for random data. Use the program here as a template. import streamlit as st
import random
# Define the dictionary lists for each organ
HEART_LIST = [
{"name": "Heartbeat", "description": "The rhythmic contraction and expansion of the heart", "emoji": "β€οΈ"},
{"name": "Blood vessels", "description": "The network of tubes that carry blood throughout the body", "emoji": "π§"},
{"name": "Pulse", "description": "The rhythmic expansion and contraction of an artery as blood flows through it", "emoji": "π"}
]
LUNG_LIST = [
{"name": "Breathing", "description": "The act of inhaling and exhaling air", "emoji": "π¬οΈ"},
{"name": "Respiration", "description": "The process by which oxygen is taken in and carbon dioxide is expelled", "emoji": "π¨"},
{"name": "Coughing", "description": "A reflex action that helps to clear the airways", "emoji": "π€§"}
]
BRAIN_LIST = [
{"name": "Memory", "description": "The ability to store and retrieve information", "emoji": "π§ "},
{"name": "Concentration", "description": "The ability to focus on a task or idea", "emoji": "π"},
{"name": "Imagination", "description": "The ability to create mental images or ideas", "emoji": "π"}
]
# Define a function to roll a 100 sided dice 10 times and return the rolls and the total score
def roll_dice():
rolls = [random.randint(1, 100) for _ in range(10)]
total_score = sum(rolls)
return rolls, total_score
# Define the Streamlit app
def app():
st.sidebar.title("Choose an organ list")
organ_list = st.sidebar.selectbox("Select an organ", ["Heart", "Lung", "Brain"])
st.write(f"## {organ_list} List")
if organ_list == "Heart":
selected_list = HEART_LIST
elif organ_list == "Lung":
selected_list = LUNG_LIST
else:
selected_list = BRAIN_LIST
st.write("### Choose an item from the list")
selected_item = st.selectbox("Select an item", [item["name"] for item in selected_list])
selected_item_dict = [item for item in selected_list if item["name"] == selected_item][0]
st.write(f"### {selected_item_dict['name']} {selected_item_dict['emoji']}")
st.write(selected_item_dict['description'])
st.write("### Roll the dice")
rolls, total_score = roll_dice()
st.write("Rolls:", rolls)
st.write("Total score:", total_score)
st.write("### Aggregated score")
scores = [roll_dice()[1] for _ in range(10)]
st.write("Scores:", scores)
st.write("Total score:", sum(scores))
if __name__ == '__main__':
app()
Sure, here's a Streamlit app that generates a Plotly Treemap chart with random data. You can replace the data with your own, or modify the code to generate different types of charts.
python
Copy code
import streamlit as st
import plotly.express as px
import random
# Define a function to generate random data
def generate_data():
labels = [f"Category {i}" for i in range(1, 11)]
values = [random.randint(1, 100) for _ in range(10)]
return {"labels": labels, "values": values}
# Define the Streamlit app
def app():
st.title("Random Treemap Chart")
st.write("This app generates a random Treemap chart using Plotly.")
data = generate_data()
fig = px.treemap(data, path=["labels"], values="values")
st.plotly_chart(fig)
if __name__ == '__main__':
app()
The generate_data() function creates a dictionary with a list of category labels and a list of corresponding values. The px.treemap() function from Plotly is used to create a Treemap chart using the data.
When the app is run, it displays a title and a brief description, and then renders the chart using st.plotly_chart(). You can run the app with streamlit run <filename> where <filename> is the name of the file containing the code.
Aaron Wacker
Add a dataset using pandas dataframe to be able to add new lists of information to the chart to include a game mechanic name as well as a short description. Action Queue
Action Retrieval
Campaign / Battle Card Driven
Card Play Conflict Resolution
Communication Limits
Cooperative Game
Critical Hits and Failures
Deck Construction
Grid Movement
Hand Management
Hexagon Grid
Legacy Game
Line of Sight
Modular Board
Once-Per-Game Abilities
Role Playing
Scenario / Mission / Campaign Game
Simultaneous Action Selection
Solo / Solitaire Game
Storytelling
Variable Player Powers
Sure, here's an updated version of the previous code that includes a Pandas DataFrame to store the data for the Treemap chart. The DataFrame includes columns for the category labels, corresponding values, game mechanics, and short descriptions.
python
Copy code
import streamlit as st
import plotly.express as px
import pandas as pd
# Define the data for the Treemap chart
data = pd.DataFrame({
"category": ["Category 1", "Category 2", "Category 3", "Category 4", "Category 5",
"Category 6", "Category 7", "Category 8", "Category 9", "Category 10"],
"value": [10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
"mechanic": ["Action Queue", "Action Retrieval", "Campaign / Battle Card Driven",
"Card Play Conflict Resolution", "Communication Limits",
"Cooperative Game", "Critical Hits and Failures", "Deck Construction",
"Grid Movement", "Hand Management"],
"description": ["Description 1", "Description 2", "Description 3", "Description 4",
"Description 5", "Description 6", "Description 7", "Description 8",
"Description 9", "Description 10"]
})
# Define the Streamlit app
def app():
st.title("Game Mechanics Treemap Chart")
st.write("This app displays a Treemap chart of game mechanics.")
fig = px.treemap(data, path=["category", "mechanic"], values="value",
color="value", hover_data=["description"])
st.plotly_chart(fig)
if __name__ == '__main__':
app()
The DataFrame is created using a dictionary with the column names as keys and the corresponding data as values. The Treemap chart is generated using px.treemap() with the DataFrame as the input, and the path, values, color, and hover_data parameters set to the appropriate columns.
You can modify the DataFrame to add or remove categories, change the values, or update the game mechanics and descriptions.
Aaron Wacker
For each one of the list items, create two random numeric values named "HealthPoints" and Coins. Add it to the datasets. Provide a download link of the dataset after the chart is drawn.
Sure, here's an updated version of the code that generates two random numeric values for each game mechanic in the list, and adds them to the DataFrame. The values are stored in the "HealthPoints" and "Coins" columns.
After the chart is drawn, a download link for the updated DataFrame is displayed. The link downloads a CSV file that can be opened in a spreadsheet program like Microsoft Excel or Google Sheets.
python
Copy code
import streamlit as st
import plotly.express as px
import pandas as pd
import numpy as np
# Define the list of game mechanics
game_mechanics = ["Action Queue", "Action Retrieval", "Campaign / Battle Card Driven",
"Card Play Conflict Resolution", "Communication Limits",
"Cooperative Game", "Critical Hits and Failures", "Deck Construction",
"Grid Movement", "Hand Management", "Hexagon Grid", "Legacy Game",
"Line of Sight", "Modular Board", "Once-Per-Game Abilities", "Role Playing",
"Scenario / Mission / Campaign Game", "Simultaneous Action Selection",
"Solo / Solitaire Game", "Storytelling", "Variable Player Powers"]
# Define a function to generate random values for each game mechanic
def generate_values():
health_points = np.random.randint(50, 100, size=len(game_mechanics))
coins = np.random.randint(10, 50, size=len(game_mechanics))
return {"HealthPoints": health_points, "Coins": coins}
# Define the Streamlit app
def app():
st.title("Game Mechanics Treemap Chart")
st.write("This app displays a Treemap chart of game mechanics.")
# Generate the data for the chart
values = generate_values()
data = pd.DataFrame({
"category": ["Category 1"] * len(game_mechanics),
"mechanic": game_mechanics,
"value": list(values.values()),
"HealthPoints": values["HealthPoints"],
"Coins": values["Coins"],
"description": ["Description"] * len(game_mechanics)
})
data["value"] = data["value"].apply(lambda x: sum(x))
# Draw the chart
fig = px.treemap(data, path=["category", "mechanic"], values="value",
color="HealthPoints", hover_data=["Coins"])
st.plotly_chart(fig)
# Display a download link for the data
csv = data.to_csv(index=False)
b64 = base64.b64encode(csv.encode()).decode()
href = f'<a href="data:file/csv;base64,{b64}" download="game_mechanics.csv">Download CSV</a>'
st.markdown(href, unsafe_allow_html=True)
if __name__ == '__main__':
app()
The generate_values() function uses NumPy to generate random values for "HealthPoints" and "Coins" for each game mechanic. The values are then added to the DataFrame in separate columns.
The data["value"] column is updated to reflect the sum of "HealthPoints" and "Coins" for each game mechanic.
A download link for the updated DataFrame is displayed using the to_csv() method to convert the DataFrame to a CSV file, and the base64 module to encode the file for download.
Aaron Wacker
In line 28 the pandas dataset has an error. Change this with refactoring to make sure all arrays are the same length: ValueError: All arrays must be of the same length
You're right, the values in the "HealthPoints" and "Coins" columns must be of the same length as the number of game mechanics in the list. To fix this error, we can modify the generate_values() function to accept the number of game mechanics as a parameter, and return random values with that length.
Here's the updated code:
python
Copy code
import streamlit as st
import plotly.express as px
import pandas as pd
import numpy as np
# Define the list of game mechanics
game_mechanics = ["Action Queue", "Action Retrieval", "Campaign / Battle Card Driven",
"Card Play Conflict Resolution", "Communication Limits",
"Cooperative Game", "Critical Hits and Failures", "Deck Construction",
"Grid Movement", "Hand Management", "Hexagon Grid", "Legacy Game",
"Line of Sight", "Modular Board", "Once-Per-Game Abilities", "Role Playing",
"Scenario / Mission / Campaign Game", "Simultaneous Action Selection",
"Solo / Solitaire Game", "Storytelling", "Variable Player Powers"]
# Define a function to generate random values for each game mechanic
def generate_values(n):
health_points = np.random.randint(50, 100, size=n)
coins = np.random.randint(10, 50, size=n)
return {"HealthPoints": health_points, "Coins": coins}
# Define the Streamlit app
def app():
st.title("Game Mechanics Treemap Chart")
st.write("This app displays a Treemap chart of game mechanics.")
# Generate the data for the chart
n = len(game_mechanics)
values = generate_values(n)
data = pd.DataFrame({
"category": ["Category 1"] * n,
"mechanic": game_mechanics,
"value": list(values.values()),
"HealthPoints": values["HealthPoints"],
"Coins": values["Coins"],
"description": ["Description"] * n
})
data["value"] = data["value"].apply(lambda x: sum(x))
# Draw the chart
fig = px.treemap(data, path=["category", "mechanic"], values="value",
color="HealthPoints", hover_data=["Coins"])
st.plotly_chart(fig)
# Display a download link for the data
csv = data.to_csv(index=False)
b64 = base64.b64encode(csv.encode()).decode()
href = f'<a href="data:file/csv;base64,{b64}" download="game_mechanics.csv">Download CSV</a>'
st.markdown(href, unsafe_allow_html=True)
if __name__ == '__main__':
app()
The generate_values() function now takes a parameter n, which is the length of the game mechanics list. The function generates random values for "HealthPoints" and "Coins" with length n.
The data DataFrame is now constructed using the |