id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
300 | figure - shows fleet that has been partially shot down figure - we can shoot aliensmaking larger bullets for testing you can test many features of the game simply by running the gamebut some features are tedious to test in the normal version of game for exampleit' lot of work to shoot down every alien on the screen multiple times to test if your code responds to an empty fleet correctly to test particular featuresyou can change certain game settings to focus on particular area for exampleyou might shrink the screen so there are fewer aliens to shoot down or increase the bullet speed and give yourself lots of bullets at once my favorite change for testing alien invasion is to use superwide bullets that remain active even after they've hit an alien (see figure - try setting bullet_width to to see how quickly you can shoot down the fleetchanges like these will help you test the game more efficiently and possibly spark ideas for giving players bonus powers (just remember to restore the settings to normal once you're finished testing feature aliens |
301 | repopulating the fleet one key feature of alien invasion is that the aliens are relentlessevery time the fleet is destroyeda new fleet should appear to make new fleet of aliens appear after fleet has been destroyedfirst check to see whether the group aliens is empty if it iswe call create_fleet(we'll perform this check in update_bullets(because that' where individual aliens are destroyedgame_ functions py def update_bullets(ai_settingsscreenshipaliensbullets)--snip-check for any bullets that have hit aliens if soget rid of the bullet and the alien collisions pygame sprite groupcollide(bulletsalienstruetrueu if len(aliens= destroy existing bullets and create new fleet bullets empty(create_fleet(ai_settingsscreenshipaliensat we check whether the group aliens is empty if it iswe get rid of any existing bullets by using the empty(methodwhich removes all the remaining sprites from group we also call create_fleet()which fills the screen with aliens again |
302 | ai_settingsscreenand shipso we need to update the call to update_bullets(in alien_invasion pyalien_ invasion py start the main loop for the game while truegf check_events(ai_settingsscreenshipbulletsship update(gf update_bullets(ai_settingsscreenshipaliensbulletsgf update_aliens(ai_settingsaliensgf update_screen(ai_settingsscreenshipaliensbulletsnow new fleet appears as soon as you destroy the current fleet speeding up the bullets if you've tried firing at the aliens in the game' current stateyou may have noticed that the bullets have slowed down bit this is because pygame is now doing more work on each pass through the loop we can increase the speed of the bullets by adjusting the value of bullet_speed_factor in settings py if we increase this value (to for example)the bullets should travel up the screen at reasonable speed againsettings py bullet settings self bullet_speed_factor self bullet_width --snip-the best value for this setting depends on the speed of your systemso find value that works for you refactoring update_bullets(let' refactor update_bullets(so it' not doing so many different tasks we'll move the code for dealing with bullet-alien collisions to separate functiongame_ functions py def update_bullets(ai_settingsscreenshipaliensbullets)--snip-get rid of bullets that have disappeared for bullet in bullets copy()if bullet rect bottom < bullets remove(bulletcheck_bullet_alien_collisions(ai_settingsscreenshipaliensbulletsdef check_bullet_alien_collisions(ai_settingsscreenshipaliensbullets)"""respond to bullet-alien collisions ""remove any bullets and aliens that have collided collisions pygame sprite groupcollide(bulletsalienstruetruealiens |
303 | destroy existing bullets and create new fleet bullets empty(create_fleet(ai_settingsscreenshipalienswe've created new functioncheck_bullet_alien_collisions()to look for collisions between bullets and aliensand to respond appropriately if the entire fleet has been destroyed this keeps update_bullets(from growing too long and simplifies further development try it yourse lf - catchcreate game that places character that you can move left and right at the bottom of the screen make ball appear at random position at the top of the screen and fall down the screen at steady rate if your character "catchesthe ball by colliding with itmake the ball disappear make new ball each time your character catches the ball or whenever the ball disappears off the bottom of the screen ending the game what' the fun and challenge in game if you can' loseif the player doesn' shoot down the fleet quickly enoughwe'll have the aliens destroy the ship if they hit it at the same timewe'll limit the number of ships player can use and we'll destroy the ship when an alien reaches the bottom of the screen we'll end the game when the player has used up all their ships detecting alien-ship collisions we'll start by checking for collisions between aliens and the ship so we can respond appropriately when an alien hits it we'll check for alien-ship collisions immediately after updating the position of each aliengame_ functions py def update_aliens(ai_settingsshipaliens)""check if the fleet is at an edgeand then update the postions of all aliens in the fleet ""check_fleet_edges(ai_settingsaliensaliens update( look for alien-ship collisions if pygame sprite spritecollideany(shipaliens)print("ship hit!!!" |
304 | group the method looks for any member of the group that' collided with the sprite and stops looping through the group as soon as it finds one member that has collided with the sprite hereit loops through the group aliens and returns the first alien it finds that has collided with ship if no collisions occurspritecollideany(returns none and the if block at won' execute if it finds an alien that' collided with the shipit returns that alien and the if block executesit prints ship hit!! (when an alien hits the shipwe'll need to do number of taskswe'll need to delete all remaining aliens and bulletsrecenter the shipand create new fleet before we write code to do all thiswe need to know that our approach for detecting alien-ship collisions works correctly writing print statement is simple way to ensure we're detecting collisions properly now we need to pass ship to update_aliens()alien_ invasion py start the main loop for the game while truegf check_events(ai_settingsscreenshipbulletsship update(gf update_bullets(ai_settingsscreenshipaliensbulletsgf update_aliens(ai_settingsshipaliensgf update_screen(ai_settingsscreenshipaliensbulletsnow when you run alien invasionship hit!!should appear in the terminal whenever an alien runs into the ship when testing this featureset alien_drop_speed to higher value such as or so that the aliens will reach your ship faster responding to alien-ship collisions now we need to figure out what happens when an alien collides with the ship instead of destroying the ship instance and creating new onewe'll count how many times the ship has been hit by tracking statistics for the game (tracking statistics will also be useful for scoring let' write new classgamestatsto track game statisticsand save it as game_stats pygame_stats py class gamestats()"""track statistics for alien invasion "" def __init__(selfai_settings)"""initialize statistics ""self ai_settings ai_settings self reset_stats(def reset_stats(self)"""initialize statistics that can change during the game ""self ships_left self ai_settings ship_limit we'll make one gamestats instance for the entire time alien invasion is runningbut we'll need to reset some statistics each time the player starts aliens |
305 | reset_stats(instead of directly in __init__(we'll call this method from __init__(so the statistics are set properly when the gamestats instance is first created ubut we'll also be able to call reset_stats(any time the player starts new game right now we have only one statisticships_leftthe value of which will change throughout the game the number of ships the player starts with is stored in settings py as ship_limitsettings py ship settings self ship_speed_factor self ship_limit we also need to make few changes in alien_invasion pyto create an instance of gamestatsalien_ invasion py --snip-from settings import settings from game_stats import gamestats --snip-def run_game()--snip-pygame display set_caption("alien invasion" create an instance to store game statistics stats gamestats(ai_settings--snip-start the main loop for the game while true--snip-gf update_bullets(ai_settingsscreenshipaliensbulletsgf update_aliens(ai_settingsstatsscreenshipaliensbullets--snip-we import the new gamestats class umake stats instance vand then add the statsscreenand ship arguments in the call to update_aliens( we'll use these arguments to track the number of ships the player has left and to build new fleet when an alien hits the ship when an alien hits the shipwe subtract one from the number of ships leftdestroy all existing aliens and bulletscreate new fleetand reposition the ship in the middle of the screen (we'll also pause the game for moment so the player can notice the collision and regroup before new fleet appears let' put most of this code in the function ship_hit()game_ import sys functions py from time import sleep import pygame --snip- |
306 | """respond to ship being hit by alien ""decrement ships_left stats ships_left - empty the list of aliens and bullets aliens empty(bullets empty( create new fleet and center the ship create_fleet(ai_settingsscreenshipaliensship center_ship( pause sleep( def update_aliens(ai_settingsstatsscreenshipaliensbullets)--snip-look for alien-ship collisions if pygame sprite spritecollideany(shipaliens)ship_hit(ai_settingsstatsscreenshipaliensbulletswe first import the sleep(function from the time module to pause the game the new function ship_hit(coordinates the response when the ship is hit by an alien inside ship_hit()the number of ships left is reduced by vafter which we empty the groups aliens and bullets nextwe create new fleet and center the ship (we'll add the method center_ship(to ship in moment finallywe pause after the updates have been made to all the game elements but before any changes have been drawn to the screen so the player can see that their ship has been hit the screen will freeze momentarilyand the player will see that the alien has hit the ship when the sleep(function endsthe code will move on to the update_screen(functionwhich will draw the new fleet to the screen we also update the definition of update_aliens(to include the parameters statsscreenand bullets so it can pass these values in the call to ship_hit(here' the new method center_ship()add it to the end of ship pyship py def center_ship(self)"""center the ship on the screen ""self center self screen_rect centerx to center the shipwe set the value of the ship' center attribute to match the center of the screenwhich we get through the screen_rect attribute note notice that we never make more than one shipwe make only one ship instance for the whole game and recenter it whenever the ship has been hit the statistic ships_left will tell us when the player has run out of ships aliens |
307 | game should pauseand new fleet should appear with the ship centered at the bottom of the screen again aliens that reach the bottom of the screen if an alien reaches the bottom of the screenwe'll respond the same way we do when an alien hits the ship add new function to perform this checkand call it from update_aliens()game_ functions py def check_aliens_bottom(ai_settingsstatsscreenshipaliensbullets)"""check if any aliens have reached the bottom of the screen ""screen_rect screen get_rect(for alien in aliens sprites() if alien rect bottom >screen_rect bottomtreat this the same as if the ship got hit ship_hit(ai_settingsstatsscreenshipaliensbulletsbreak def update_aliens(ai_settingsstatsscreenshipaliensbullets)--snip-look for aliens hitting the bottom of the screen check_aliens_bottom(ai_settingsstatsscreenshipaliensbulletsthe function check_aliens_bottom(checks to see whether any aliens have reached the bottom of the screen an alien reaches the bottom when its rect bottom value is greater than or equal to the screen' rect bottom attribute if an alien reaches the bottomwe call ship_hit(if one alien hits the bottomthere' no need to check the restso we break out of the loop after calling ship_hit(we call check_aliens_bottom(after updating the positions of all the aliens and after looking for alien-ship collisions now new fleet will appear every time the ship is hit by an alien or an alien reaches the bottom of the screen game overalien invasion feels more complete nowbut the game never ends the value of ships_left just grows increasingly negative let' add game_active flag as an attribute to gamestats to end the game when the player runs out of shipsgame_stats py def __init__(selfsettings)--snip-start alien invasion in an active state self game_active true |
308 | has used up all their shipsgame_ functions py def ship_hit(ai_settingsstatsscreenshipaliensbullets)"""respond to ship being hit by alien ""if stats ships_left decrement ships_left stats ships_left - --snip-pause sleep( elsestats game_active false most of ship_hit(is unchanged we've moved all of the existing code into an if blockwhich tests to make sure the player has at least one ship remaining if sowe create new fleetpauseand move on if the player has no ships leftwe set game_active to false identifying when parts of the game should run in alien_invasion py we need to identify the parts of the game that should always run and the parts that should run only when the game is activealien_ invasion py start the main loop for the game while truegf check_events(ai_settingsscreenshipbulletsif stats game_activeship update(gf update_bullets(ai_settingsscreenshipaliensbulletsgf update_aliens(ai_settingsstatsscreenshipaliensbulletsgf update_screen(ai_settingsscreenshipaliensbulletsin the main loopwe always need to call check_events()even if the game is inactive for examplewe still need to know if the user presses to quit the game or clicks the button to close the window we also continue updating the screen so we can make changes to the screen while waiting to see whether the player chooses to start new game the rest of the function calls only need to happen when the game is activebecause when the game is inactivewe don' need to update the positions of game elements now when you play alien invasionthe game should freeze when you've used up all of your ships aliens |
309 | - game overusing your code from exercise - (page )keep track of the number of times the player misses the ball when they've missed the ball three timesend the game summary in this you learned how to add large number of identical elements to game by creating fleet of aliens you learned how to use nested loops to create grid of elementsand you made large set of game elements move by calling each element' update(method you learned to control the direction of objects on the screen and how to respond to eventssuch as when the fleet reaches the edge of the screen you also learned how to detect and respond to collisions when bullets hit aliens and aliens hit the ship finallyyou learned how to track the statistics in game and use game_active flag to determine when the game was over in the final of this projectwe'll add play button so the player can choose when to start their first game and whether to play again when the game ends we'll speed up the game each time the player shoots down the entire fleetand we'll add scoring system the final result will be fully playable game |
310 | sc in this we'll finish the alien invasion game we'll add play button to start game on demand or to restart game once it ends we'll also change the game so it speeds up when the player moves up leveland we'll implement scoring system by the end of the you'll know enough to start writing games that increase in difficulty as player progresses and that show scores |
311 | in this section we'll add play button that appears before game begins and reappears when the game ends so the player can play again right now the game begins as soon as you run alien_invasion py let' start the game in an inactive state and then prompt the player to click play button to begin to do thisenter the following in game_stats pygame_stats py def __init__(selfai_settings)"""initialize statistics ""self ai_settings ai_settings self reset_stats(start game in an inactive state self game_active false def reset_stats(self)--snip-now the game should start in an inactive state with no way for the player to start it until we make play button creating button class because pygame doesn' have built-in method for making buttonswe'll write button class to create filled rectangle with label you can use this code to make any button in game here' the first part of the button classsave it as button pybutton py import pygame font class button() def __init__(selfai_settingsscreenmsg)"""initialize button attributes ""self screen screen self screen_rect screen get_rect(set the dimensions and properties of the button self widthself height self button_color ( self text_color ( self font pygame font sysfont(none build the button' rect object and center it self rect pygame rect( self widthself heightself rect center self screen_rect center the button message needs to be prepped only once self prep_msg(msg |
312 | text to the screen the __init__(method takes the parameters selfthe ai_settings and screen objectsand msgwhich contains the text for the button we set the button dimensions at vand then we set button_color to color the button' rect object bright green and set text_color to render the text in white at we prepare font attribute for rendering text the none argument tells pygame to use the default fontand determines the size of the text to center the button on the screenwe create rect for the button and set its center attribute to match that of the screen pygame works with text by rendering the string you want to display as an image at we call prep_msg(to handle this rendering here' the code for prep_msg()button py def prep_msg(selfmsg)"""turn msg into rendered image and center text on the button ""self msg_image self font render(msgtrueself text_colorself button_colorself msg_image_rect self msg_image get_rect(self msg_image_rect center self rect center the prep_msg(method needs self parameter and the text to be rendered as an image (msgthe call to font render(turns the text stored in msg into an imagewhich we then store in msg_image the font render(method also takes boolean value to turn antialiasing on or off (antialiasing makes the edges of the text smootherthe remaining arguments are the specified font color and background color we set antialiasing to true and set the text background to the same color as the button (if you don' include background colorpygame will try to render the font with transparent background at we center the text image on the button by creating rect from the image and setting its center attribute to match that of the button finallywe create draw_button(method that we can call to display the button onscreenbutton py def draw_button(self)draw blank button and then draw message self screen fill(self button_colorself rectself screen blit(self msg_imageself msg_image_rectwe call screen fill(to draw the rectangular portion of the button then we call screen blit(to draw the text image to the screenpassing it an image and the rect object associated with the image this completes the button class scoring |
313 | we'll use the button class to create play button because we need only one play buttonwe'll create the button directly in alien_invasion py as shown herealien_ invasion py --snip-from game_stats import gamestats from button import button --snip-def run_game()--snip-pygame display set_caption("alien invasion" make the play button play_button button(ai_settingsscreen"play"--snip-start the main loop for the game while true--snip-gf update_screen(ai_settingsscreenstatsshipaliensbulletsplay_buttonrun_game(we import button and create an instance called play_button uand then we pass play_button to update_screen(so the button appears when the screen updates nextmodify update_screen(so the play button appears only when the game is inactivegame_ functions py def update_screen(ai_settingsscreenstatsshipaliensbulletsplay_button)"""update images on the screen and flip to the new screen ""--snip-draw the play button if the game is inactive if not stats game_activeplay_button draw_button(make the most recently drawn screen visible pygame display flip(to make the play button visible above all other elements on the screenwe draw it after all other game elements have been drawn and before flipping to new screen now when you run alien invasion you should see play button in the center of the screenas shown in figure - |
314 | starting the game to start new game when the player clicks playadd the following code to game_functions py to monitor mouse events over the buttongame_ functions py def check_events(ai_settingsscreenstatsplay_buttonshipbullets)"""respond to keypresses and mouse events ""for event in pygame event get()if event type =pygame quit--snip- elif event type =pygame mousebuttondownv mouse_xmouse_y pygame mouse get_pos( check_play_button(statsplay_buttonmouse_xmouse_ydef check_play_button(statsplay_buttonmouse_xmouse_y)"""start new game when the player clicks play "" if play_button rect collidepoint(mouse_xmouse_y)stats game_active true we've updated the definition of check_events(to accept the stats and play_button parameters we'll use stats to access the game_active flag and play_button to check whether the play button has been clicked pygame detects mousebuttondown event when the player clicks anywhere on the screen ubut we want to restrict our game to respond to mouse clicks only on the play button to accomplish thiswe use pygame mouse get_pos()which returns tuple containing the xand -coordinates of the mouse cursor when the mouse button is clicked we send these values to the function check_play_button(wwhich uses collidepoint(to see if the point of the mouse click overlaps the region defined by the play button' rect if sowe set game_active to trueand the game beginsscoring |
315 | alien_ invasion py start the main loop for the game while truegf check_events(ai_settingsscreenstatsplay_buttonshipbullets--snip-at this pointyou should be able to start and play full game when the game endsthe value of game_active should become false and the play button should reappear resetting the game the code we just wrote works the first time the player clicks play but not once the first game endsbecause the conditions that caused the game to end haven' been reset to reset the game each time the player clicks playwe need to reset the game statisticsclear out the old aliens and bulletsbuild new fleetand center the shipas shown heregame_ functions py def check_play_button(ai_settingsscreenstatsplay_buttonshipaliensbulletsmouse_xmouse_y)"""start new game when the player clicks play ""if play_button rect collidepoint(mouse_xmouse_y)reset the game statistics stats reset_stats(stats game_active true empty the list of aliens and bullets aliens empty(bullets empty( create new fleet and center the ship create_fleet(ai_settingsscreenshipaliensship center_ship(we update the definition of check_play_button(so it has access to ai_settingsstatsshipaliensand bullets it needs these objects to reset the settings that have changed during the game and to refresh the visual elements of the game at we reset the game statisticswhich gives the player three new ships then we set game_active to true (so the game will begin as soon as the code in this function finishes running)empty the aliens and bullets groups vand create new fleet and center the ship |
316 | to check_play_button()game_ functions py def check_events(ai_settingsscreenstatsplay_buttonshipaliensbullets)"""respond to keypresses and mouse events ""for event in pygame event get()if event type =pygame quit--snip-elif event type =pygame mousebuttondownmouse_xmouse_y pygame mouse get_pos( check_play_button(ai_settingsscreenstatsplay_buttonshipaliensbulletsmouse_xmouse_ythe definition of check_events(needs the aliens parameterwhich it will pass to check_play_button(we then update the call to check_play_button(so it passes the appropriate arguments now update the call to check_events(in alien_invasion py so it passes the aliens argumentalien_ invasion py start the main loop for the game while truegf check_events(ai_settingsscreenstatsplay_buttonshipaliensbullets--snip-the game will now reset properly each time you click playallowing you to play it as many times as you wantdeactivating the play button one issue with our play button is that the button region on the screen will continue to respond to clicks even when the play button isn' visible click the play button area by accident once game has begun and the game will restartto fix thisset the game to start only when game_active is falsegame_ functions py def check_play_button(ai_settingsscreenstatsplay_buttonshipaliensbulletsmouse_xmouse_y)"""start new game when the player clicks play "" button_clicked play_button rect collidepoint(mouse_xmouse_yv if button_clicked and not stats game_activereset the game statistics --snip-the flag button_clicked stores true or false value uand the game will restart only if play is clicked and the game is not currently active to test this behaviorstart new game and repeatedly click where the play button should be if everything works as expectedclicking the play button area should have no effect on the gameplay scoring |
317 | we want the mouse cursor visible in order to begin playbut once play begins it only gets in the way to fix thiswe'll make it invisible once the game becomes activegame_ functions py def check_play_button(ai_settingsscreenstatsplay_buttonshipaliensbulletsmouse_xmouse_y)"""start new game when the player clicks play ""button_clicked play_button rect collidepoint(mouse_xmouse_yif button_clicked and not stats game_activehide the mouse cursor pygame mouse set_visible(false--snip-passing false to set_visible(tells pygame to hide the cursor when the mouse is over the game window we'll make the cursor reappear once the game ends so the player can click play to begin new game here' the code to do thatgame_ functions py def ship_hit(ai_settingsscreenstatsshipaliensbullets)"""respond to ship being hit by alien ""if stats ships_left --snip-elsestats game_active false pygame mouse set_visible(truewe make the cursor visible again as soon as the game becomes inactivewhich happens in ship_hit(attention to details like this makes your game seem more professional and allows the player to focus on playing rather than figuring out the user interface try it yourse lf - press to playbecause alien invasion uses keyboard input to control the shipit' best to start the game with keypress add code that lets the player press to start it may help to move some code from check_play_button(to start_game(function that can be called from both check_play_button(and check_keydown_events( - target practicecreate rectangle at the right edge of the screen that moves up and down at steady rate then have ship appear on the left side of the screen that the player can move up and down while firing bullets at the movingrectangular target add play button that starts the gameand when the player misses the target three timesend the game and make the play button reappear let the player restart the game with this play button |
318 | in our current gameonce player shoots down the entire alien fleetthe player reaches new levelbut the game difficulty doesn' change let' liven things up bit and make the game more challenging by increasing the speed of the game each time player clears the screen modifying the speed settings we'll first reorganize the settings class to group the game settings into static and changing ones we'll also make sure that settings that change over the course of game reset when we start new game here' the __init__(method for settings pysettings py def __init__(self)"""initialize the game' static settings ""screen settings self screen_width self screen_height self bg_color ( ship settings self ship_limit bullet settings self bullet_width self bullet_height self bullet_color self bullets_allowed alien settings self fleet_drop_speed how quickly the game speeds up self speedup_scale self initialize_dynamic_settings(we continue to initialize the settings that stay constant in the __init__(method at we add speedup_scale setting to control how quickly the game speeds upa value of will double the game speed every time the player reaches new levela value of will keep the speed constant speed value like should increase the speed enough to make the game challenging but not impossible finallywe call initialize_dynamic_settings(to initialize the values for attributes that need to change throughout the course of game here' the code for initialize_dynamic_settings()settings py def initialize_dynamic_settings(self)"""initialize settings that change throughout the game ""self ship_speed_factor self bullet_speed_factor scoring |
319 | fleet_direction of represents right- represents left self fleet_direction this method sets the initial values for the shipbulletand alien speeds we'll increase these speeds as the player progresses in the game and reset them each time the player starts new game we include fleet_direction in this method so the aliens always move right at the beginning of new game to increase the speeds of the shipbulletsand aliens each time the player reaches new leveluse increase_speed()settings py def increase_speed(self)"""increase speed settings ""self ship_speed_factor *self speedup_scale self bullet_speed_factor *self speedup_scale self alien_speed_factor *self speedup_scale to increase the speed of these game elementswe multiply each speed setting by the value of speedup_scale we increase the game' tempo by calling increase_speed(in check_ bullet_alien_collisions(when the last alien in fleet has been shot down but before creating new fleetgame_ functions py def check_bullet_alien_collisions(ai_settingsscreenshipaliensbullets)--snip-if len(aliens= destroy existing bulletsspeed up gameand create new fleet bullets empty(ai_settings increase_speed(create_fleet(ai_settingsscreenshipalienschanging the values of the speed settings ship_speed_factoralien_speed_ factorand bullet_speed_factor is enough to speed up the entire gameresetting the speed we need to return any changed settings to their initial values each time the player starts new gameor each new game would start with the increased speed settings of the previous gamegame_ functions py def check_play_button(ai_settingsscreenstatsplay_buttonshipaliensbulletsmouse_xmouse_y)"""start new game when the player clicks play ""button_clicked play_button rect collidepoint(mouse_xmouse_yif button_clicked and not stats game_activereset the game settings ai_settings initialize_dynamic_settings(hide the mouse cursor pygame mouse set_visible(false--snip- |
320 | time you clear the screenthe game should speed up and become slightly more difficult if the game becomes too difficult too quicklydecrease the value of settings speedup_scaleor if the game isn' challenging enoughincrease the value slightly find sweet spot by ramping up the difficulty in reasonable amount of time the first couple of screens should be easythe next few challenging but doableand subsequent screens almost impossibly difficult try it yourse lf - challenging target practicestart with your work from exercise - (page make the target move faster as the game progressesand restart at the original speed when the player clicks play scoring let' implement scoring system to track the game' score in real timeas well as to display the high scoreleveland the number of ships remaining the score is game statisticso we'll add score attribute to gamestatsgame_stats py class gamestats()--snip-def reset_stats(self)"""initialize statistics that can change during the game ""self ships_left self ai_settings ship_limit self score to reset the score each time new game startswe initialize score in reset_stats(rather than __init__(displaying the score to display the score on the screenwe first create new classscoreboard for now this class will just display the current scorebut we'll use it to report the high scoreleveland number of ships remaining as well here' the first part of the classsave it as scoreboard pyscoreboard py import pygame font class scoreboard()""" class to report scoring information "" def __init__(selfai_settingsscreenstats)"""initialize scorekeeping attributes ""self screen screen scoring |
321 | self ai_settings ai_settings self stats stats font settings for scoring information self text_color ( self font pygame font sysfont(none prepare the initial score image self prep_score(because scoreboard writes text to the screenwe begin by importing the pygame font module nextwe give __init__(the parameters ai_settingsscreenand stats so it can report the values we're tracking thenwe set text color and instantiate font object to turn the text to be displayed into an imagewe call prep_score(xwhich we define herescoreboard py def prep_score(self)"""turn the score into rendered image ""score_str str(self stats scoreself score_image self font render(score_strtrueself text_colorself ai_settings bg_colordisplay the score at the top right of the screen self score_rect self score_image get_rect(self score_rect right self screen_rect right self score_rect top in prep_score()we first turn the numerical value stats score into string uand then pass this string to render()which creates the image to display the score clearly onscreenwe pass the screen' background color to render(as well as text color we'll position the score in the upper-right corner of the screen and have it expand to the left as the score increases and the width of the number grows to make sure the score always lines up with the right side of the screenwe create rect called score_rect and set its right edge pixels from the right screen edge we then place the top edge pixels down from the top of the screen finallywe create show_score(method to display the rendered score imagescoreboard py def show_score(self)"""draw score to the screen ""self screen blit(self score_imageself score_rectthis method draws the score image to the screen at the location specified by score_rect |
322 | to display the scorewe'll create scoreboard instance in alien_invasion pyalien_ invasion py --snip-from game_stats import gamestats from scoreboard import scoreboard --snip-def run_game()--snip-create an instance to store game statistics and create scoreboard stats gamestats(ai_settingsu sb scoreboard(ai_settingsscreenstats--snip-start the main loop for the game while true--snip- gf update_screen(ai_settingsscreenstatssbshipaliensbulletsplay_buttonrun_game(we import the new scoreboard class and make an instance called sb after creating the stats instance we then pass sb to update_screen(so the score can be drawn to the screen to display the scoremodify update_screen(like thisgame_ functions py def update_screen(ai_settingsscreenstatssbshipaliensbulletsplay_button)--snip-draw the score information sb show_score(draw the play button if the game is inactive if not stats game_activeplay_button draw_button(make the most recently drawn screen visible pygame display flip(we add sb to the list of parameters that define update_screen(and call show_score(just before the play button is drawn when you run alien invasion nowyou should see at the top right of the screen (for now we just want to make sure that the score appears in the right place before developing the scoring system further figure - shows the score as it appears before the game starts scoring |
323 | now to assign point values to each alienupdating the score as aliens are shot down to write live score to the screenwe update the value of stats score whenever an alien is hitand then call prep_score(to update the score image but firstlet' determine how many points player gets each time they shoot down an aliensettings py def initialize_dynamic_settings(self)--snip-scoring self alien_points we'll increase the point value of each alien as the game progresses to make sure this point value is reset each time new game startswe set the value in initialize_dynamic_settings(update the score each time an alien is shot down in check_bullet_alien_ collisions()game_ functions py def check_bullet_alien_collisions(ai_settingsscreenstatssbshipaliensbullets)"""respond to bullet-alien collisions ""remove any bullets and aliens that have collided collisions pygame sprite groupcollide(bulletsalienstruetrue |
324 | if collisionsstats score +ai_settings alien_points sb prep_score(--snip-we update the definition of check_bullet_alien_collisions(to include the stats and sb parameters so it can update the score and the scoreboard when bullet hits an alienpygame returns collisions dictionary we check whether the dictionary existsand if it doesthe alien' value is added to the score we then call prep_score(to create new image for the updated score we need to modify update_bullets(to make sure the appropriate arguments are passed between functionsgame_ functions py def update_bullets(ai_settingsscreenstatssbshipaliensbullets)"""update position of bullets and get rid of old bullets ""--snip-check_bullet_alien_collisions(ai_settingsscreenstatssbshipaliensbulletsthe definition of update_bullets(needs the additional parameters stats and sb the call to check_bullet_alien_collisions(needs to include the stats and sb arguments as well we also need to modify the call to update_bullets(in the main while loopalien_ invasion py start the main loop for the game while truegf check_events(ai_settingsscreenstatsplay_buttonshipaliensbulletsif stats game_activeship update(gf update_bullets(ai_settingsscreenstatssbshipaliensbullets--snip-the call to update_bullets(needs the stats and sb arguments now when you play alien invasionyou should be able to rack up pointsmaking sure to score all hits as currently writtenour code could miss some aliens for exampleif two bullets collide with aliens during the same pass through the loop or if we make an extra wide bullet to hit multiple aliensthe player will receive points only for one of the aliens killed to fix thislet' refine the way that alien bullet collisions are detected scoring |
325 | becomes key in the collisions dictionary the value associated with each bullet is list of aliens it has collided with we loop through the collisions dictionary to make sure we award points for each alien hitgame_ functions py def check_bullet_alien_collisions(ai_settingsscreenstatssbshipaliensbullets)--snip-if collisionsu for aliens in collisions values()stats score +ai_settings alien_points len(alienssb prep_score(--snip-if the collisions dictionary has been definedwe loop through all values in the collisions dictionary remember that each value is list of aliens hit by single bullet we multiply the value of each alien by the number of aliens in each list and add this amount to the current score to test thischange the width of bullet to pixels and verify that you receive points for each alien you hit with your extra wide bulletsthen return the bullet width to normal increasing point values because the game gets more difficult each time player reaches new levelaliens in later levels should be worth more points to implement this functionalitywe'll add code to increase the point value when the game' speed increasessettings py class settings()""" class to store all settings for alien invasion "" def __init__(self)--snip-how quickly the game speeds up self speedup_scale how quickly the alien point values increase self score_scale self initialize_dynamic_settings(def increase_speed(self)"""increase speed settings and alien point values ""self ship_speed_factor *self speedup_scale self bullet_speed_factor *self speedup_scale self alien_speed_factor *self speedup_scale self alien_points int(self alien_points self score_scalewe define rate at which points increasewhich we call score_scale small increase in speed ( makes the game grow challenging quickly |
326 | alien point value by larger amount ( now when we increase the speed of the gamewe also increase the point value of each hit we use the int(function to increase the point value by whole integers to see the value of each alienadd print statement to the method increase_speed(in settingssettings py def increase_speed(self)--snip-self alien_points int(self alien_points self score_scaleprint(self alien_pointsyou should see the new point value in the terminal every time you reach new level be sure to remove the print statement after verifying that the point value is increasingor it may affect the performance of your game and distract the player note rounding the score most arcade-style shooting games report scores as multiples of so let' follow that lead with our scoring let' also format the score to include comma separators in large numbers we'll make this change in scoreboardscoreboard py def prep_score(self)"""turn the score into rendered image ""rounded_score int(round(self stats score- )score_str "{:,}format(rounded_scoreself score_image self font render(score_strtrueself text_colorself ai_settings bg_color--snip-the round(function normally rounds decimal number to set number of decimal places given as the second argument howeverif you pass negative number as the second argumentround(will round the value to the nearest and so on the code at tells python to round the value of stats score to the nearest and store it in rounded_score note in python round(always returns decimal valueso we use int(to make sure the score is reported as an integer if you're using python you can leave out the call to int(at va string formatting directive tells python to insert commas into numbers when converting numerical value to string--for exampleto output , , instead of now when you run the gameyou should see neatly formattedrounded score even when you rack up lots of pointsas shown in figure - scoring |
327 | high scores every player wants to beat game' high scoreso let' track and report high scores to give players something to work toward we'll store high scores in gamestatsgame_stats py def __init__(selfai_settings)--snip-high score should never be reset self high_score because the high score should never be resetwe initialize high_score in __init__(rather than in reset_stats(now we'll modify scoreboard to display the high score let' start with the __init__(methodscoreboard py def __init__(selfai_settingsscreenstats)--snip-prepare the initial score images self prep_score(self prep_high_score(the high score will be displayed separately from the scoreso we need new methodprep_high_score()to prepare the high score image here' the prep_high_score(methodscoreboard py def prep_high_score(self)"""turn the high score into rendered image ""high_score int(round(self stats high_score- ) |
328 | high_score_str "{:,}format(high_scoreself high_score_image self font render(high_score_strtrueself text_colorself ai_settings bg_colorcenter the high score at the top of the screen self high_score_rect self high_score_image get_rect(self high_score_rect centerx self screen_rect centerx self high_score_rect top self score_rect top we round the high score to the nearest and format it with commas we then generate an image from the high score wcenter the high score rect horizontally xand set its top attribute to match the top of the score image the show_score(method now draws the current score at the top right and the high score at the top center of the screenscoreboard py def show_score(self)"""draw the score to the screen ""self screen blit(self score_imageself score_rectself screen blit(self high_score_imageself high_score_rectto check for high scoreswe'll write new functioncheck_high_score()in game_functions pygame_ functions py def check_high_score(statssb)"""check to see if there' new high score "" if stats score stats high_scorestats high_score stats score sb prep_high_score(the function check_high_score(takes two parametersstats and sb it uses stats to check the current score and the high scoreand it needs sb to modify the high score image when necessary at we check the current score against the high score if the current score is greaterwe update the value of high_score and call prep_high_score(to update the image of the high score we need to call check_high_score(each time an alien is hit after updating the score in check_bullet_alien_collisions()game_ functions py def check_bullet_alien_collisions(ai_settingsscreenstatssbshipaliensbullets)--snip-if collisionsfor aliens in collisions values()stats score +ai_settings alien_points len(alienssb prep_score(check_high_score(statssb--snip-we call check_high_score(when the collisions dictionary is presentand we do so after updating the score for all the aliens that have been hit scoring |
329 | scoreso it will be displayed as both the current and high score but when you start second gameyour high score should appear in the middle and your current score at the rightas shown in figure - figure - the high score is shown at the top center of the screen displaying the level to display the player' level in the gamewe first need an attribute in gamestats representing the current level to reset the level at the start of each new gameinitialize it in reset_stats()game_stats py def reset_stats(self)"""initialize statistics that can change during the game ""self ships_left self ai_settings ship_limit self score self level to have scoreboard display the current level (just below the current score)we call new methodprep_level()from __init__()scoreboard py def __init__(selfai_settingsscreenstats)--snip-prepare the initial score images self prep_score(self prep_high_score(self prep_level( |
330 | scoreboard py def prep_level(self)"""turn the level into rendered image ""self level_image self font render(str(self stats level)trueself text_colorself ai_settings bg_colorposition the level below the score self level_rect self level_image get_rect(self level_rect right self score_rect right self level_rect top self score_rect bottom the method prep_level(creates an image from the value stored in stats level and sets the image' right attribute to match the score' right attribute it then sets the top attribute pixels beneath the bottom of the score image to leave space between the score and the level we also need to update show_score()scoreboard py def show_score(self)"""draw scores and ships to the screen ""self screen blit(self score_imageself score_rectself screen blit(self high_score_imageself high_score_rectself screen blit(self level_imageself level_rectthis adds line to draw the level image to the screen we'll increment stats level and update the level image in check_bullet_ alien_collisions()game_ functions py def check_bullet_alien_collisions(ai_settingsscreenstatssbshipaliensbullets)--snip-if len(aliens= if the entire fleet is destroyedstart new level bullets empty(ai_settings increase_speed( increase level stats level + sb prep_level(create_fleet(ai_settingsscreenshipaliensif fleet is destroyedwe increment the value of stats level and call prep_level(to make sure the new level is displayed correctly to make sure the scoring and level images are updated properly at the start of new gametrigger reset when the play button is clickedgame_ functions py def check_play_button(ai_settingsscreenstatssbplay_buttonshipaliensbulletsmouse_xmouse_y)"""start new game when the player clicks play ""button_clicked play_button rect collidepoint(mouse_xmouse_yif button_clicked and not stats game_activescoring |
331 | stats reset_stats(stats game_active true reset the scoreboard images sb prep_score(sb prep_high_score(sb prep_level(empty the list of aliens and bullets aliens empty(bullets empty(--snip-the definition of check_play_button(needs the sb object to reset the scoreboard imageswe call prep_score()prep_high_score()and prep_level(after resetting the relevant game settings now pass sb from check_events(so check_play_button(has access to the scoreboard objectgame_ functions py def check_events(ai_settingsscreenstatssbplay_buttonshipaliensbullets)"""respond to keypresses and mouse events ""for event in pygame event get()if event type =pygame quit--snip-elif event type =pygame mousebuttondownmouse_xmouse_y pygame mouse get_pos( check_play_button(ai_settingsscreenstatssbplay_buttonshipaliensbulletsmouse_xmouse_ythe definition of check_events(needs sb as parameterso the call to check_play_button(can include sb as an argument finallyupdate the call to check_events(in alien_invasion py so it passes sb as wellalien_ invasion py start the main loop for the game while truegf check_events(ai_settingsscreenstatssbplay_buttonshipaliensbullets--snip-now you can see how many levels you've completedas shown in figure - |
332 | in some classic gamesthe scores have labelssuch as scorehigh scoreand level we've omitted these labels because the meaning of each number becomes clear once you've played the game to include these labelsadd them to the score strings just before the calls to font render(in scoreboard note displaying the number of ships finallylet' display the number of ships the player has leftbut this timelet' use graphic to do sowe'll draw ships in the upper-left corner of the screen to represent how many ships are leftlike many classic arcade games do firstwe need to make ship inherit from sprite so we can create group of shipsship py import pygame from pygame sprite import sprite class ship(sprite) def __init__(selfai_settingsscreen)"""initialize the ship and set its starting position ""super(shipself__init__(--snip-here we import spritemake sure ship inherits from sprite uand call super(at the beginning of __init__( scoring |
333 | display here' the import statements and __init__()scoreboard py import pygame font from pygame sprite import group from ship import ship class scoreboard()""" class to report scoring information ""def __init__(selfai_settingsscreenstats)--snip-self prep_level(self prep_ships(--snip-because we're making group of shipswe import the group and ship classes we call prep_ships(after the call to prep_level(here' prep_ships()scoreboard py def prep_ships(self)"""show how many ships are left ""self ships group(for ship_number in range(self stats ships_left)ship ship(self ai_settingsself screenship rect ship_number ship rect width ship rect self ships add(shipthe prep_ships(method creates an empty groupself shipsto hold the ship instances to fill this groupa loop runs once for every ship the player has left inside the loop we create new ship and set each ship' -coordinate value so the ships appear next to each other with -pixel margin on the left side of the group of ships we set the -coordinate value pixels down from the top of the screen so the ships line up with the score image finallywe add each new ship to the group ships now we need to draw the ships to the screenscoreboard py def show_score(self)--snip-self screen blit(self level_imageself level_rectdraw ships self ships draw(self screento display the ships on the screenwe call draw(on the groupand pygame draws each ship |
334 | prep_ships(when new game starts we do this in check_play_button(in game_functions pygame_ functions py def check_play_button(ai_settingsscreenstatssbplay_buttonshipaliensbulletsmouse_xmouse_y)"""start new game when the player clicks play ""button_clicked play_button rect collidepoint(mouse_xmouse_yif button_clicked and not stats game_active--snip-reset the scoreboard images sb prep_score(sb prep_high_score(sb prep_level(sb prep_ships(--snip-we also call prep_ships(when ship is hit to update the display of ship images when the player loses shipgame_ def update_aliens(ai_settingsscreenstatssbshipaliensbullets)functions py --snip-look for alien-ship collisions if pygame sprite spritecollideany(shipaliens) ship_hit(ai_settingsscreenstatssbshipaliensbulletsw look for aliens hitting the bottom of the screen check_aliens_bottom(ai_settingsscreenstatssbshipaliensbulletsx def ship_hit(ai_settingsscreenstatssbshipaliensbullets)"""respond to ship being hit by alien ""if stats ships_left decrement ships_left stats ships_left - update scoreboard sb prep_ships(empty the list of aliens and bullets --snip-we first add the parameter sb to the definition of update_aliens( we then pass sb to ship_hit( and check_aliens_bottom(so each has access to the scoreboard object then we update the definition of ship_hit(to include sb we call prep_ships(after decreasing the value of ships_left yso the correct number of ships is displayed each time ship is destroyed scoring |
335 | game_ functions py def check_aliens_bottom(ai_settingsscreenstatssbshipaliensbullets)"""check if any aliens have reached the bottom of the screen ""screen_rect screen get_rect(for alien in aliens sprites()if alien rect bottom >screen_rect bottomtreat this the same as if ship got hit ship_hit(ai_settingsscreenstatssbshipaliensbulletsbreak now check_aliens_bottom(accepts sb as parameterand we add an sb argument in the call to ship_hit(finallypass sb in the call to update_aliens(in alien_invasion pyalien_ invasion py start the main loop for the game while true--snip-if stats game_activeship update(gf update_bullets(ai_settingsscreenstatssbshipaliensbulletsgf update_aliens(ai_settingsscreenstatssbshipaliensbullets--snip-figure - shows the complete scoring system with the remaining ships displayed at the top left of the screen figure - the complete scoring system for alien invasion |
336 | - all-time high scorethe high score is reset every time player closes and restarts alien invasion fix this by writing the high score to file before calling sys exit(and reading the high score in when initializing its value in gamestats - refactoringlook for functions and methods that are doing more than one taskand refactor them to keep your code organized and efficient for examplemove some of the code in check_bullet_alien_collisions()which starts new level when the fleet of aliens has been destroyedto function called start_new_level(alsomove the four separate method calls in the __init__(method in scoreboard to method called prep_images(to shorten __init__(the prep_images(method could also help check_play_button(or start_game(if you've already refactored check_play_button(note before attempting to refactor the projectsee appendix to learn how to restore the project to working state if you introduce bugs while refactoring - expanding alien invasionthink of way to expand alien invasion for exampleyou could program the aliens to shoot bullets down at the ship or add shields for your ship to hide behindwhich can be destroyed by bullets from either side or use something like the pygame mixer module to add sound effects like explosions and shooting sounds summary in this you learned to build play button to start new game and how to detect mouse events and hide the cursor in active games you can use what you've learned to create other buttons in your gameslike help button to display instructions on how to play you also learned how to modify the speed of game as it progresseshow to implement progressive scoring systemand how to display information in textual and nontextual ways scoring |
337 | data isua li at ion |
338 | ge ne at ing data data visualization involves exploring data through visual representations it' closely associated with data miningwhich uses code to explore the patterns and connections in data set data set can be just small list of numbers that fits in one line of code or many gigabytes of data making beautiful representations of data is about more than pretty pictures when you have simplevisually appealing representation of data setits meaning becomes clear to viewers people will see patterns and significance in your data sets that they never knew existed fortunatelyyou don' need supercomputer to visualize complex data with python' efficiencyyou can quickly explore data sets made of millions of individual data points on just laptop the data points don' have to be numberseither with the basics you learned in the first part of this bookyou can analyze nonnumerical data as well people use python for data-intensive work in geneticsclimate researchpolitical and economic analysisand much more data scientists have written an impressive array of visualization and analysis tools in pythonmany |
339 | matplotliba mathematical plotting library we'll use matplotlib to make simple plotssuch as line graphs and scatter plots after whichwe'll create more interesting data set based on the concept of random walk-- visualization generated from series of random decisions we'll also use package called pygalwhich focuses on creating visualizations that work well on digital devices you can use pygal to emphasize and resize elements as the user interacts with your visualizationand you can easily resize the entire representation to fit on tiny smartwatch or giant monitor we'll use pygal to explore what happens when you roll dice in various ways installing matplotlib firstyou'll need to install matplotlibwhich we'll use for our initial set of visualizations if you haven' used pip yetsee "installing python packages with pipon page on linux if you're using the version of python that came with your systemyou can use your system' package manager to install matplotlib using just one linesudo apt-get install python -matplotlib if you're running python use this linesudo apt-get install python-matplotlib if you installed newer version of pythonyou'll have to install few libraries that matplotlib depends onsudo apt-get install python -dev python -tk tk-dev sudo apt-get install libfreetype -dev +then use pip to install matplotlibpip install --user matplotlib on os apple includes matplotlib with its standard python installation to check whether it' installed on your systemopen terminal session and try import matplotlib if matplotlib isn' already on your system and you used homebrew to install pythoninstall it like thispip install --user matplotlib |
340 | you might need to use pip instead of pip when installing packages alsoif this command doesn' workyou might need to leave off the --user flag on windows on windowsyou'll first need to install visual studio go to windows com/click downloadsand look for visual studio communitywhich is free set of developer tools for windows download and run the installer next you'll need an installer for matplotlib go to pypi/matplotliband look for wheel file ( file ending in whlthat matches the version of python you're using for exampleif you're using -bit version of python you'll need to download matplotlib--cp -none-win whl note if you don' see file matching your installed version of pythonlook at what' available at tends to release installers little earlier than the official matplotlib site copy the whl file to your project folderopen command windowand navigate to the project folder then use pip to install matplotlibcd python_work python_workpython - pip install --user matplotlib--cp -none-win whl testing matplotlib after you've installed the necessary packagestest your installation by starting terminal session with the python or python command and importing matplotlibpython import matplotlib if you don' see any error messagesthen matplotlib is installed on your systemand you can move on to the next section note if you have trouble with your installationsee appendix if all else failsask for help your issue will most likely be one that an experienced python programmer can troubleshoot quickly with little information from you the matplotlib gallery to see the kinds of visualizations you can make with matplotlibvisit the sample gallery at galleryyou can see the code used to generate the plot generating data |
341 | let' plot simple line graph using matplotliband then customize it to create more informative visualization of our data we'll use the square number sequence as the data for the graph just provide matplotlib with the numbers as shown hereand matplotlib should do the restmpl_squares py import matplotlib pyplot as plt squares [ plt plot(squaresplt show(we first import the pyplot module using the alias plt so we don' have to type pyplot repeatedly (you'll see this convention often in online examplesso we'll do the same here pyplot contains number of functions that help generate charts and plots we create list to hold the squares and then pass it to the plot(functionwhich will try to plot the numbers in meaningful way plt show(opens matplotlib' viewer and displays the plotas shown in figure - the viewer allows you to zoom and navigate the plotand if you click the disk iconyou can save any plot images you like figure - one of the simplest plots you can make in matplotlib changing the label type and graph thickness although the plot shown in figure - shows that the numbers are increasingthe label type is too small and the line is too thin fortunatelymatplotlib allows you to adjust every feature of visualization |
342 | mpl_squares py import matplotlib pyplot as plt squares [ plt plot(squareslinewidth= set chart title and label axes plt title("square numbers"fontsize= plt xlabel("value"fontsize= plt ylabel("square of value"fontsize= set size of tick labels plt tick_params(axis='both'labelsize= plt show(the linewidth parameter at controls the thickness of the line that plot(generates the title(function at sets title for the chart the fontsize parameterswhich appear repeatedly throughout the codecontrol the size of the text on the chart the xlabel(and ylabel(functions allow you to set title for each of the axes wand the function tick_params(styles the tick marks the arguments shown here affect the tick marks on both the xand -axes (axes='both'and set the font size of the tick mark labels to (labelsize= as you can see in figure - the resulting chart is much easier to read the label type is biggerand the line graph is thicker figure - the chart is much easier to read now generating data |
343 | but now that we can read the chart betterwe see that the data is not plotted correctly notice at the end of the graph that the square of is shown as let' fix that when you give plot( sequence of numbersit assumes the first data point corresponds to an -coordinate value of but our first point corresponds to an -value of we can override the default behavior by giving plot(both the input and output values used to calculate the squaresmpl_squares py import matplotlib pyplot as plt input_values [ squares [ plt plot(input_valuessquareslinewidth= set chart title and label axes --snip-now plot(will graph the data correctly because we've provided both the input and output valuesso it doesn' have to assume how the output numbers were generated the resulting plotshown in figure - is correct figure - the data is now plotted correctly you can specify numerous arguments when using plot(and use number of functions to customize your plots we'll continue to explore these customization functions as we work with more interesting data sets throughout this plotting and styling individual points with scatter(sometimes it' useful to be able to plot and style individual points based on certain characteristics for exampleyou might plot small values in one |
344 | set with one set of styling options and then emphasize individual points by replotting them with different options to plot single pointuse the scatter(function pass the single (xyvalues of the point of interest to scatter()and it should plot those valuesscatter_ squares py import matplotlib pyplot as plt plt scatter( plt show(let' style the output to make it more interesting we'll add titlelabel the axesand make sure all the text is large enough to readimport matplotlib pyplot as plt plt scatter( = set chart title and label axes plt title("square numbers"fontsize= plt xlabel("value"fontsize= plt ylabel("square of value"fontsize= set size of tick labels plt tick_params(axis='both'which='major'labelsize= plt show(at we call scatter(and use the argument to set the size of the dots used to draw the graph when you run scatter_squares py nowyou should see single point in the middle of the chartas shown in figure - figure - plotting single point generating data |
345 | to plot series of pointswe can pass scatter(separate lists of xand -valueslike thisscatter_ squares py import matplotlib pyplot as plt x_values [ y_values [ plt scatter(x_valuesy_valuess= set chart title and label axes --snip-the x_values list contains the numbers to be squaredand y_values contains the square of each number when these lists are passed to scatter()matplotlib reads one value from each list as it plots each point the points to be plotted are ( )( )( )( )and ( )the result is shown in figure - figure - scatter plot with multiple points calculating data automatically writing out lists by hand can be inefficientespecially when we have many points rather than passing our points in listlet' use loop in python to do the calculations for us here' how this would look with pointsscatter_ squares py import matplotlib pyplot as plt x_values list(range( )y_values [ ** for in x_valuesv plt scatter(x_valuesy_valuess= |
346 | --snip-set the range for each axis plt axis([ ]plt show(we start with list of -values containing the numbers through nexta list comprehension generates the -values by looping through the -values (for in x_values)squaring each number ( ** )and storing the results in y_values we then pass the input and output lists to scatter( because this is large data setwe use smaller point size and we use the axis(function to specify the range of each axis the axis(function requires four valuesthe minimum and maximum values for the -axis and the -axis herewe run the -axis from to and the -axis from to , , figure - shows the result figure - python can plot points as easily as it plots points removing outlines from data points matplotlib lets you color points individually in scatter plot the default-blue dots with black outline--works well for plots with few points but when plotting many pointsthe black outlines can blend together to remove the outlines around pointspass the argument edgecolor='nonewhen you call scatter()plt scatter(x_valuesy_valuesedgecolor='none' = run scatter_squares py using this calland you should see only solid blue points in your plot generating data |
347 | to change the color of the pointspass to scatter(with the name of color to useas shown hereplt scatter(x_valuesy_valuesc='red'edgecolor='none' = you can also define custom colors using the rgb color model to define colorpass the argument tuple with three decimal values (one each for redgreenand blue)using values between and for examplethe following line would create plot with light blue dotsplt scatter(x_valuesy_valuesc=( )edgecolor='none' = values closer to produce dark colorsand values closer to produce lighter colors using colormap colormap is series of colors in gradient that moves from starting to ending color colormaps are used in visualizations to emphasize pattern in the data for exampleyou might make low values light color and high values darker color the pyplot module includes set of built-in colormaps to use one of these colormapsyou need to specify how pyplot should assign color to each point in the data set here' how to assign each point color based on its -valuescatter_ squares py import matplotlib pyplot as plt x_values list(range( )y_values [ ** for in x_valuesplt scatter(x_valuesy_valuesc=y_valuescmap=plt cm bluesedgecolor='none' = set chart title and label axes --snip-we pass the list of -values to and then tell pyplot which colormap to use through the cmap argument this code colors the points with lower -values light blue and the points with larger -values dark blue the resulting plot is shown in figure - note you can see all the colormaps available in pyplot at examplesscroll down to color examplesand click colormaps_reference |
348 | saving your plots automatically if you want your program to automatically save the plot to fileyou can replace the call to plt show(with call to plt savefig()plt savefig('squares_plot png'bbox_inches='tight'the first argument is filename for the plot imagewhich will be saved in the same directory as scatter_squares py the second argument trims extra whitespace from the plot if you want the extra whitespace around the plotyou can omit this argument try it yourse lf - cubesa number raised to the third power is cube plot the first five cubic numbersand then plot the first cubic numbers - colored cubesapply colormap to your cubes plot random walks in this section we'll use python to generate data for random walk and then use matplotlib to create visually appealing representation of the generated data random walk is path that has no clear direction but is generating data |
349 | chance you might imagine random walk as the path an ant would take if it had lost its mind and took every step in random direction random walks have practical applications in naturephysicsbiologychemistryand economics for examplea pollen grain floating on drop of water moves across the surface of the water because it is constantly being pushed around by water molecules molecular motion in water drop is randomso the path pollen grain traces out on the surface is random walk the code we're about to write models many real-world situations creating the randomwalk(class to create random walkwe'll create randomwalk classwhich will make random decisions about which direction the walk should take the class needs three attributesone variable to store the number of points in the walk and two lists to store the xand -coordinate values of each point in the walk we'll use only two methods for the randomwalk classthe __init__(method and fill_walk()which will calculate the points in the walk let' start with __init__(as shown hererandom_ from random import choice walk py class randomwalk()""" class to generate random walks "" def __init__(selfnum_points= )"""initialize attributes of walk ""self num_points num_points all walks start at ( self x_values [ self y_values [ to make random decisionswe'll store possible choices in list and use choice(to decide which choice to use each time decision is made we then set the default number of points in walk to --large enough to generate some interesting patterns but small enough to generate walks quickly then at we make two lists to hold the xand -valuesand we start each walk at point ( choosing directions we'll use fill_walk()as shown hereto fill our walk with points and determine the direction of each step add this method to random_walk pyrandom_ walk py def fill_walk(self)"""calculate all the points in the walk "" keep taking steps until the walk reaches the desired length while len(self x_valuesself num_points |
350 | decide which direction to go and how far to go in that direction x_direction choice([ - ]x_distance choice([ ]x_step x_direction x_distance y_direction choice([ - ]y_distance choice([ ]y_step y_direction y_distance reject moves that go nowhere if x_step = and y_step = continue calculate the next and values next_x self x_values[- x_step next_y self y_values[- y_step self x_values append(next_xself y_values append(next_yat we set up loop that runs until the walk is filled with the correct number of points the main part of this method tells python how to simulate four random decisionswill the walk go right or lefthow far will it go in that directionwill it go up or downhow far will it go in that directionwe use choice([ - ]to choose value for x_directionwhich returns either for right movement or - for left nextchoice([ ]tells python how far to move in that direction (x_distanceby randomly selecting an integer between and (the inclusion of allows us to take steps along the -axis as well as steps that have movement along both axes at and we determine the length of each step in the and directions by multiplying the direction of movement by the distance chosen positive result for x_step moves us righta negative result moves us leftand moves us vertically positive result for y_step means move upnegative means move downand means move horizontally if the value of both x_step and y_step are the walk stopsbut we continue the loop to prevent this to get the next -value for our walkwe add the value in x_step to the last value stored in x_values and do the same for the -values once we have these valueswe append them to x_values and y_values plotting the random walk here' the code to plot all the points in the walkrw_visual py import matplotlib pyplot as plt from random_walk import randomwalk make random walkand plot the points rw randomwalk(rw fill_walk(generating data |
351 | plt show(we begin by importing pyplot and randomwalk we then create random walk and store it in rw umaking sure to call fill_walk(at we feed the walk' xand -values to scatter(and choose an appropriate dot size figure - shows the resulting plot with points (the images in this section omit matplotlib' viewerbut you'll continue to see it when you run rw_visual py figure - random walk with points generating multiple random walks every random walk is differentand it' fun to explore the various patterns that can be generated one way to use the preceding code to make multiple walks without having to run the program several times is to wrap it in while looplike thisrw_visual py import matplotlib pyplot as plt from random_walk import randomwalk keep making new walksas long as the program is active while truemake random walkand plot the points rw randomwalk(rw fill_walk(plt scatter(rw x_valuesrw y_valuess= plt show( keep_running input("make another walk( / )"if keep_running =' 'break |
352 | and pause with the viewer open when you close the vieweryou'll be asked whether you want to generate another walk answer yand you should be able to generate walks that stay near the starting pointthat wander off mostly in one directionthat have thin sections connecting larger groups of pointsand so on when you want to end the programenter if you're using python remember to use raw_input(instead of input(at note styling the walk in this section we'll customize our plots to emphasize the important characteristics of each walk and deemphasize distracting elements to do sowe identify the characteristics we want to emphasizesuch as where the walk beganwhere it endedand the path taken nextwe identify the characteristics to deemphasizelike tick marks and labels the result should be simple visual representation that clearly communicates the path taken in each random walk coloring the points we'll use colormap to show the order of the points in the walk and then remove the black outline from each dot so the color of the dots will be clearer to color the points according to their position in the walkwe pass the argument list containing the position of each point because the points are plotted in orderthe list just contains the numbers from to as shown hererw_visual py --snip-while truemake random walkand plot the points rw randomwalk(rw fill_walk( point_numbers list(range(rw num_points)plt scatter(rw x_valuesrw y_valuesc=point_numberscmap=plt cm bluesedgecolor='none' = plt show(keep_running input("make another walk( / )"--snip-at we use range(to generate list of numbers equal to the number of points in the walk then we store them in the list point_numberswhich we'll use to set the color of each point in the walk we pass point_numbers to the argumentuse the blues colormapand then pass edgecolor=none to get rid of the black outline around each point the result is plot of the walk that varies from light to dark blue along gradientas shown in figure - generating data |
353 | plotting the starting and ending points in addition to coloring points to show their position along the walkit would be nice to see where each walk begins and ends to do sowe can plot the first and last points individually once the main series has been plotted we'll make the end points larger and color them differently to make them stand outas shown hererw_visual py --snip-while true--snip-plt scatter(rw x_valuesrw y_valuesc=point_numberscmap=plt cm bluesedgecolor='none' = emphasize the first and last points plt scatter( ='green'edgecolors='none' = plt scatter(rw x_values[- ]rw y_values[- ] ='red'edgecolors='none' = plt show(--snip-to show the starting pointwe plot point ( in green in larger size ( = than the rest of the points to mark the end pointwe plot the last xand -value in the walk in red with size of make sure you insert this code just before the call to plt show(so the starting and ending points are drawn on top of all the other points when you run this codeyou should be able to spot exactly where each walk begins and ends (if these end points don' stand out clearlyadjust their color and size until they do |
354 | let' remove the axes in this plot so they don' distract us from the path of each walk to turn the axes offuse this coderw_visual py --snip-while true--snip-plt scatter(rw x_values[- ]rw y_values[- ] ='red'edgecolors='none' = remove the axes plt axes(get_xaxis(set_visible(falseplt axes(get_yaxis(set_visible(falseplt show(--snip-to modify the axesuse the plt axes(function to set the visibility of each axis to false as you continue to work with visualizationsyou'll frequently see this chaining of methods run rw_visual py nowyou should see series of plots with no axes adding plot points let' increase the number of points to give us more data to work with to do sowe increase the value of num_points when we make randomwalk instance and adjust the size of each dot when drawing the plotas shown hererw_visual py --snip-while truemake random walkand plot the points rw randomwalk( rw fill_walk(plot the pointsand show the plot point_numbers list(range(rw num_points)plt scatter(rw x_valuesrw y_valuesc=point_numberscmap=plt cm bluesedgecolor='none' = --snip-this example creates random walk with , points (to mirror realworld dataand plots each point at size = the resulting walk is wispy and cloud-likeas shown in figure - as you can seewe've created piece of art from simple scatter plotexperiment with this code to see how much you can increase the number of points in walk before your system starts to slow down significantly or the plot loses its visual appeal generating data |
355 | altering the size to fill the screen visualization is much more effective at communicating patterns in data if it fits nicely on the screen to make the plotting window better fit your screenadjust the size of matplotlib' outputlike thisrw_visual py --snip-while truemake random walkand plot the points rw randomwalk(rw fill_walk(set the size of the plotting window plt figure(figsize=( )--snip-the figure(function controls the widthheightresolutionand background color of the plot the figsize parameter takes tuplewhich tells matplotlib the dimensions of the plotting window in inches python assumes that your screen resolution is pixels per inchif this code doesn' give you an accurate plot sizeadjust the numbers as necessary orif you know your system' resolutionpass figure(the resolution using the dpi parameter to set plot size that makes effective use of the space available on your screenas shown hereplt figure(dpi= figsize=( ) |
356 | - molecular motionmodify rw_visual py by replacing plt scatter(with plt plot(to simulate the path of pollen grain on the surface of drop of waterpass in the rw x_values and rw y_valuesand include linewidth argument use instead of , points - modified random walksin the class randomwalkx_step and y_step are generated from the same set of conditions the direction is chosen randomly from the list [ - and the distance from the list [ modify the values in these lists to see what happens to the overall shape of your walks try longer list of choices for the distancesuch as through or remove the - from the or direction list - refactoringthe method fill_walk(is lengthy create new method called get_step(to determine the direction and distance for each stepand then calculate the step you should end up with two calls to get_step(in fill_walk()x_step get_step(y_step get_step(this refactoring should reduce the size of fill_walk(and make the method easier to read and understand rolling dice with pygal in this section we'll use the python visualization package pygal to produce scalable vector graphics files these are useful in visualizations that are presented on differently sized screens because they scale automatically to fit the viewer' screen if you plan to use your visualizations onlineconsider using pygal so your work will look good on any device people use to view your visualizations in this project we'll analyze the results of rolling dice if you roll one regular six-sided dieyou have an equal chance of rolling any of the numbers from through howeverwhen using two diceyou're more likely to roll certain numbers rather than others we'll try to determine which numbers are most likely to occur by generating data set that represents rolling dice then we'll plot the results of large number of rolls to determine which results are more likely than others the study of rolling dice is often used in mathematics to explain various types of data analysis but it also has real-world applications in casinos and other gambling scenariosas well as in the way games like monopoly and many role-playing games are played generating data |
357 | install pygal with pip (if you haven' used pip yetsee "installing python packages with pipon page on linux and os xthis should be something likepip install --user pygal on windowsthis should bepython - pip install --user pygal you may need to use the command pip instead of pipand if the command still doesn' work you may need to leave off the --user flag note the pygal gallery to see what kind of visualizations are possible with pygalvisit the gallery of chart typesgo to chart types each example includes source codeso you can see how the visualizations are generated creating the die class here' class to simulate the roll of one diedie py from random import randint class die()""" class representing single die "" def __init__(selfnum_sides= )"""assume six-sided die ""self num_sides num_sides def roll(self)""""return random value between and number of sides ""return randint( self num_sidesthe __init__(method takes one optional argument with this classwhen an instance of our die is createdthe number of sides will always be six if no argument is included if an argument is includedthat value is used to set the number of sides on the die (dice are named for their number of sidesa six-sided die is an eight-sided die is and so on the roll(method uses the randint(function to return random number between and the number of sides this function can return the starting value ( )the ending value (num_sides)or any integer between the two |
358 | before creating visualization based on this classlet' roll print the resultsand check that the results look reasonabledie_visual py from die import die create die die(make some rollsand store results in list results [ for roll_num in range( )result die roll(results append(resultprint(resultsat we create an instance of die with the default six sides at we roll the die times and store the results of each roll in the list results here' sample set of results[ quick scan of these results shows that the die class seems to be working we see the values and so we know the smallest and largest possible values are being returnedand because we don' see or we know all the results are in the appropriate range we also see each number from through which indicates that all possible outcomes are represented analyzing the results we analyze the results of rolling one by counting how many times we roll each numberdie_visual py --snip-make some rollsand store results in list results [ for roll_num in range( )result die roll(results append(resultanalyze the results frequencies [ for value in range( die num_sides+ )frequency results count(valuefrequencies append(frequencyprint(frequenciesgenerating data |
359 | increase the number of simulated rolls to to analyze the rollswe create the empty list frequencies to store the number of times each value is rolled we loop through the possible values ( through in this caseat vcount how many times each number appears in results and then append this value to the frequencies list we then print this list before making visualization[ these results look reasonablewe see six frequenciesone for each possible number when you roll and we see that no frequency is significantly higher than any other now let' visualize these results making histogram with list of frequencieswe can make histogram of the results histogram is bar chart showing how often certain results occur here' the code to create the histogramdie_visual py import pygal --snip-analyze the results frequencies [for value in range( die num_sides+ )frequency results count(valuefrequencies append(frequencyvisualize the results hist pygal bar(hist title "results of rolling one times hist x_labels [' '' '' '' '' '' 'hist x_title "resulthist y_title "frequency of resultw hist add(' 'frequencieshist render_to_file('die_visual svg'we make bar chart by creating an instance of pygal bar()which we store in hist we then set the title attribute of hist (just string we use to label the histogram)use the possible results of rolling as the labels for the -axis vand add title for each of the axes we use add(to add series of values to the chart at (passing it label for the set of values to be added and list of the values to appear on the chartfinallywe render the chart to an svg filewhich expects filename with the svg extension the simplest way to look at the resulting histogram is in web browser open new tab in any web browser and then open the file die_visual svg (in the folder where you saved die_visual pyyou should see chart like the |
360 | pygal generates charts with darker background than what you see here figure - simple bar chart created with pygal notice that pygal has made the chart interactivehover your cursor over any bar in the chart and you'll see the data associated with it this feature is particularly useful when plotting multiple data sets on the same chart rolling two dice rolling two dice results in larger numbers and different distribution of results let' modify our code to create two dice to simulate the way we roll pair of dice each time we roll the pairwe'll add the two numbers (one from each dieand store the sum in results save copy of die_visual py as dice_visual pyand make the following changesdice_visual py import pygal from die import die create two dice die_ die(die_ die(make some rollsand store results in list results [for roll_num in range( ) result die_ roll(die_ roll(results append(resultanalyze the results frequencies [ max_result die_ num_sides die_ num_sides generating data |
361 | frequency results count(valuefrequencies append(frequencyvisualize the results hist pygal bar( hist title "results of rolling two dice times hist x_labels [' '' '' '' '' '' '' '' '' '' '' 'hist x_title "resulthist y_title "frequency of resulthist add(' 'frequencieshist render_to_file('dice_visual svg'after creating two instances of diewe roll the dice and calculate the sum of the two dice for each roll the largest possible result ( is the sum of the largest number on both dicewhich we store in max_result the smallest possible result ( is the sum of the smallest number on both dice when we analyze the resultswe count the number of results for each value between and max_result (we could have used range( )but this would work only for two dice when modeling real-world situationsit' best to write code that can easily model variety of situations this code allows us to simulate rolling pair of dice with any number of sides when creating the chartwe update the title and the labels for the -axis and data series (if the list x_labels were much longerit would make sense to write loop to generate this list automatically after running this coderefresh the tab in your browser showing the chartyou should see chart like the one in figure - figure - simulated results of rolling two six-sided dice times |
362 | you roll pair of dice as you can seeyou're least likely to roll or and most likely to roll because there are six ways to roll namely and and and and and or and rolling dice of different sizes let' create six-sided die and ten-sided dieand see what happens when we roll them , timesdifferent_ dice py from die import die import pygal create and die_ die( die_ die( make some rollsand store results in list results [for roll_num in range( )result die_ roll(die_ roll(results append(resultanalyze the results --snip-visualize the results hist pygal bar( hist title "results of rolling and , times hist x_labels [' '' '' '' '' '' '' '' '' '' '' '' '' '' '' 'hist x_title "resulthist y_title "frequency of resulthist add(' 'frequencieshist render_to_file('dice_visual svg'to make we pass the argument when creating the second die instance and change the first loop to simulate , rolls instead of the lowest possible result is still but the largest result is now so we adjust the titlex-axis labelsand data series labels to reflect that figure - shows the resulting chart instead of one most likely resultthere are five this happens because there' still only one way to roll the smallest value ( and and the largest value ( and )but the smaller die limits the number of ways you can generate the middle numbersthere are six ways to roll and thereforethese are the most common resultsand you're equally likely to roll any one of these numbers generating data |
363 | our ability to use pygal to model the rolling of dice gives us considerable freedom in exploring this phenomenon in just minutes you can simulate tremendous number of rolls using large variety of dice try it yourse lf - automatic labelsmodify die py and dice_visual py by replacing the list we used to set the value of hist x_labels with loop to generate this list automatically if you're comfortable with list comprehensionstry replacing the other for loops in die_visual py and dice_visual py with comprehensions as well - two screate simulation showing what happens if you roll two eightsided dice times increase the number of rolls gradually until you start to see the limits of your system' capabilities - three diceif you roll three dicethe smallest number you can roll is and the largest number is create visualization that shows what happens when you roll three dice - multiplicationwhen you roll two diceyou usually add the two numbers together to get the result create visualization that shows what happens if you multiply these numbers instead - practicing with both librariestry using matplotlib to make die-rolling visualizationand use pygal to make the visualization for random walk |
364 | in this you learned to generate data sets and create visualizations of that data you learned to create simple plots with matplotliband you saw how to use scatter plot to explore random walks you learned to create histogram with pygal and how to use histogram to explore the results of rolling dice of different sizes generating your own data sets with code is an interesting and powerful way to model and explore wide variety of real-world situations as you continue to work through the data visualization projects that followkeep an eye out for situations you might be able to model with code look at the visualizations you see in news mediaand see if you can identify those that were generated using methods similar to the ones you're learning in these projects in we'll download data from online sources and continue to use matplotlib and pygal to explore that data generating data |
365 | di in this you'll download data sets from online sources and create working visualizations of that data an incredible variety of data can be found onlinemuch of which hasn' been examined thoroughly the ability to analyze this data allows you to discover patterns and connections that no one else has found we'll access and visualize data stored in two common data formatscsv and json we'll use python' csv module to process weather data stored in the csv (comma-separated valuesformat and analyze high and low temperatures over time in two different locations we'll then use matplotlib to generate chart based on our downloaded data to display |
366 | and death valleycalifornia later in the we'll use the json module to access population data stored in the json format and use pygal to draw population map by country by the end of this you'll be prepared to work with different types and formats of data setsand you'll have deeper understanding of how to build complex visualizations the ability to access and visualize online data of different types and formats is essential to working with wide variety of real-world data sets the csv file format one simple way to store data in text file is to write the data as series of values separated by commascalled comma-separated values the resulting files are called csv files for examplehere' one line of weather data in csv format, , , , , ,- , , , , , , ,,,, , ,, , ,, this is weather data for january in sitkaalaska it includes the day' high and low temperaturesas well as number of other measurements from that day csv files can be tricky for humans to readbut they're easy for programs to process and extract values fromwhich speeds up the data analysis process we'll begin with small set of csv-formatted weather data recorded in sitkawhich is available in the book' resources through nostarch com/pythoncrashcoursecopy the file sitka_weather_ - csv to the folder where you're writing this programs (once you download the book' resourcesyou'll have all the files you need for this project note the weather data in this project was originally downloaded from wunderground com/historyparsing the csv file headers python' csv module in the standard library parses the lines in csv file and allows us to quickly extract the values we're interested in let' start by examining the first line of the filewhich contains series of headers for the datahighs_lows py import csv filename 'sitka_weather_ - csvu with open(filenameas fv reader csv reader(fw header_row next(readerprint(header_row |
367 | working with in filename we then open the file and store the resulting file object in nextwe call csv reader(and pass it the file object as an argument to create reader object associated with that file we store the reader object in reader the csv module contains next(functionwhich returns the next line in the file when passed the reader object in the preceding listing we call next(only once so we get the first line of the filewhich contains the file headers we store the data that' returned in header_row as you can seeheader_row contains meaningful weather-related headers that tell us what information each line of data holds['akdt''max temperaturef''mean temperaturef''min temperaturef''max dew pointf''meandew pointf''min dewpointf''max humidity'mean humidity'min humidity'max sea level pressurein'mean sea level pressurein'min sea level pressurein'max visibilitymiles'mean visibilitymiles'min visibilitymiles'max wind speedmph'mean wind speedmph'max gust speedmph''precipitationin'cloudcover'events'winddirdegrees'reader processes the first line of comma-separated values in the file and stores each as an item in list the header akdt represents alaska daylight time the position of this header tells us that the first value in each line will be the date or time the max temperaturef header tells us that the second value in each line is the maximum temperature for that datein degrees fahrenheit you can read through the rest of the headers to determine the kind of information included in the file the headers are not always formatted consistentlyspaces and units are in odd places this is common in raw data files but won' cause problem note printing the headers and their positions to make it easier to understand the file header dataprint each header and its position in the listhighs_lows py --snip-with open(filenameas freader csv reader(fheader_row next(readeru for indexcolumn_header in enumerate(header_row)print(indexcolumn_headerwe use enumerate( on the list to get the index of each itemas well as the value (note that we've removed the line print(header_rowin favor of this more detailed version downloading data |
368 | akdt max temperaturef mean temperaturef min temperaturef --snip- cloudcover events winddirdegrees here we see that the dates and their high temperatures are stored in columns and to explore this datawe'll process each row of data in sitka_weather_ - csv and extract the values with the indices and extracting and reading data now that we know which columns of data we needlet' read in some of that data firstwe'll read in the high temperature for each dayhighs_lows py import csv get high temperatures from file filename 'sitka_weather_ - csvwith open(filenameas freader csv reader(fheader_row next(readeru highs [for row in readerhighs append(row[ ]print(highswe make an empty list called highs and then loop through the remaining rows in the file the reader object continues from where it left off in the csv file and automatically returns each line following its current position because we've already read the header rowthe loop will begin at the second line where the actual data begins on each pass through the loopwe append the data from index the second columnto highs the following listing shows the data now stored in highs[' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' 'we've extracted the high temperature for each date and stored them neatly in list as strings |
369 | matplotlibhighs_lows py --snip-highs [for row in readeru high int(row[ ]highs append(highprint(highswe convert the strings to integers at before appending the temperatures to the list the result is list of daily highs in numerical format[ now let' create visualization of this data plotting data in temperature chart to visualize the temperature data we havewe'll first create simple plot of the daily highs using matplotlibas shown herehighs_lows py import csv from matplotlib import pyplot as plt get high temperatures from file --snip-plot data fig plt figure(dpi= figsize=( ) plt plot(highsc='red'format plot plt title("daily high temperaturesjuly "fontsize= plt xlabel(''fontsize= plt ylabel("temperature ( )"fontsize= plt tick_params(axis='both'which='major'labelsize= plt show(we pass the list of highs to plot( and pass ='redto plot the points in red (we'll plot the highs in red and the lows in blue we then specify few other formatting detailssuch as font size and labels vwhich you should recognize from because we have yet to add the dateswe won' label the -axisbut plt xlabel(does modify the font size to make the default labels more readable figure - shows the resulting plota simple line graph of the high temperatures for july in sitkaalaska downloading data |
370 | the datetime module let' add dates to our graph to make it more useful the first date from the weather data file is in the second row of the file, , , , , , , , , , ,--snip-the data will be read in as stringso we need way to convert the string 'to an object representing this date we can construct an object representing july using the strptime(method from the datetime module let' see how strptime(works in terminal sessionfrom datetime import datetime first_date datetime strptime('''% -% -% 'print(first_date : : we first import the datetime class from the datetime module then we call the method strptime(with the string containing the date we want to work with as the first argument the second argument tells python how the date is formatted in this example'% -tells python to interpret the part of the string before the first dash as four-digit year'% -tells python to interpret the part of the string before the second dash as number representing the monthand '%dtells python to interpret the last part of the string as the day of the monthfrom to the strptime(method can take variety of arguments to determine how to interpret the date table - shows some of these arguments |
371 | argument meaning % weekday namesuch as monday % month namesuch as january % monthas number ( to % day of the monthas number ( to % four-digit yearsuch as % two-digit yearsuch as % hourin -hour format ( to % hourin -hour format ( to % am or pm % minutes ( to % seconds ( to plotting dates knowing how to process the dates in our csv filewe can now improve our plot of the temperature data by extracting dates for the daily highs and passing the dates and the highs to plot()as shown herehighs_lows py import csv from datetime import datetime from matplotlib import pyplot as plt get dates and high temperatures from file filename 'sitka_weather_ - csvwith open(filenameas freader csv reader(fheader_row next(readeru dateshighs [][for row in readercurrent_date datetime strptime(row[ ]"% -% -% "dates append(current_datehigh int(row[ ]highs append(highplot data fig plt figure(dpi= figsize=( ) plt plot(dateshighsc='red'format plot plt title("daily high temperaturesjuly "fontsize= plt xlabel(''fontsize= downloading data |
372 | plt ylabel("temperature ( )"fontsize= plt tick_params(axis='both'which='major'labelsize= plt show(we create two empty lists to store the dates and high temperatures from the file we then convert the data containing the date information (row[ ]to datetime object and append it to dates we pass the dates and the high temperature values to plot(at the call to fig autofmt_xdate(at draws the date labels diagonally to prevent them from overlapping figure - shows the improved graph figure - the graph is more meaningful now that it has dates on the -axis plotting longer timeframe with our graph set uplet' add more data to get more complete picture of the weather in sitka copy the file sitka_weather_ csvwhich contains full year' worth of weather underground data for sitkato the folder where you're storing this programs now we can generate graph for the entire year' weatherhighs_lows py --snip-get dates and high temperatures from file filename 'sitka_weather_ csvwith open(filenameas --snip-format plot plt title("daily high temperatures "fontsize= plt xlabel(''fontsize= --snip- |
373 | and we update the title of our plot to reflect the change in its content figure - shows the resulting plot figure - year' worth of data plotting second data series the reworked graph in figure - displays substantial amount of meaningful databut we can make it even more useful by including the low temperatures we need to extract the low temperatures from the data file and then add them to our graphas shown herehighs_lows py --snip-get dateshighand low temperatures from file filename 'sitka_weather_ csvwith open(filenameas freader csv reader(fheader_row next(readeru dateshighslows [][][for row in readercurrent_date datetime strptime(row[ ]"% -% -% "dates append(current_datehigh int(row[ ]highs append(highv low int(row[ ]lows append(lowdownloading data |
374 | fig plt figure(dpi= figsize=( )plt plot(dateshighsc='red' plt plot(dateslowsc='blue'format plot plt title("daily high and low temperatures "fontsize= --snip-at we add the empty list lows to hold low temperaturesand then we extract and store the low temperature for each datefrom the fourth position in each row (row[ ] at we add call to plot(for the low temperatures and color these values blue finallywe update the title figure - shows the resulting chart figure - two data series on the same plot shading an area in the chart having added two data serieswe can now examine the range of temperatures for each day let' add finishing touch to the graph by using shading to show the range between each day' high and low temperatures to do sowe'll use the fill_between(methodwhich takes series of -values and two series of -valuesand fills the space between the two -value serieshighs_lows py --snip-plot data fig plt figure(dpi= figsize=( ) plt plot(dateshighsc='red'alpha= plt plot(dateslowsc='blue'alpha= plt fill_between(dateshighslowsfacecolor='blue'alpha= --snip- |
375 | of is completely transparentand (the defaultis completely opaque by setting alpha to we make the red and blue plot lines appear lighter at we pass fill_between(the list dates for the -values and then the two -value series highs and lows the facecolor argument determines the color of the shaded regionand we give it low alpha value of so the filled region connects the two data series without distracting from the information they represent figure - shows the plot with the shaded region between the highs and lows figure - the region between the two data sets is shaded the shading helps make the range between the two data sets immediately apparent error-checking we should be able to run the code from highs_lows py using data for any location but some weather stations occasionally malfunction and fail to collect some or all of the data they're supposed to missing data can result in exceptions that crash our programs if we don' handle them properly for examplelet' see what happens when we attempt to generate temperature plot for death valleycalifornia copy the file death_valley_ csv to the folder where you're storing this programsand then change highs_lows py to generate graph for death valleyhighs_lows py --snip-get dateshighand low temperatures from file filename 'death_valley_ csvwith open(filenameas --snip-downloading data |
376 | the following outputtraceback (most recent call last)file "highs_lows py"line in high int(row[ ]valueerrorinvalid literal for int(with base 'the traceback tells us that python can' process the high temperature for one of the dates because it can' turn an empty string (''into an integer look through death_valley_ csv shows the problem,,,,,,,,,,,,,,,,,,, ,,,- it seems that on february no data was recordedthe string for the high temperature is empty to address this issuewe'll run errorchecking code when the values are being read from the csv file to handle exceptions that might arise when we parse our data sets here' how that workshighs_lows py --snip-get dateshigh and low temperatures from file filename 'death_valley_ csvwith open(filenameas freader csv reader(fheader_row next(readeru dateshighslows [][][for row in readertrycurrent_date datetime strptime(row[ ]"% -% -% "high int(row[ ]low int(row[ ]except valueerrorprint(current_date'missing data'elsedates append(current_datehighs append(highlows append(lowplot data --snip-format plot title "daily high and low temperatures \ndeath valleycaplt title(titlefontsize= --snip- |
377 | high and low temperature if any data is missingpython will raise valueerror and we handle it by printing an error message that includes the date of the missing data after printing the errorthe loop will continue processing the next row if all data for date is retrieved without errorthe else block will run and the data will be appended to the appropriate lists because we're plotting information for new locationwe update the title to include the location on the plot when you run highs_lows py nowyou'll see that only one date had missing datamissing data figure - shows the resulting plot figure - daily high and low temperatures for death valley comparing this graph to the sitka graphwe can see that death valley is warmer overall than southeast alaskaas might be expectedbut also that the range of temperatures each day is actually greater in the desert the height of the shaded region makes this clear many data sets you work with will have missing dataimproperly formatted dataor incorrect data use the tools you learned in the first half of this book to deal with these situations here we used tryexceptelse block to handle missing data sometimes you'll use continue to skip over some data or use remove(or del to eliminate some data after it' been extracted you can use any approach that worksas long as the result is meaningfulaccurate visualization downloading data |
378 | - san franciscoare temperatures in san francisco more like temperatures in sitka or temperatures in death valleygenerate high-low temperature plot for san francisco and make comparison (you can download weather data for almost any location from enter location and date rangescroll to the bottom of the pageand find link labeled comma-delimited file right-click this linkand save the data as csv file - sitka-death valley comparisonthe temperature scales on the sitka and death valley graphs reflect the different ranges of the data to accurately compare the temperature range in sitka to that of death valleyyou need identical scales on the -axis change the settings for the -axis on one or both of the charts in figures - and - and make direct comparison between temperature ranges in sitka and death valley (or any two places you want to compareyou can also try plotting the two data sets on the same chart - rainfallchoose any location you're interested inand make visualization that plots its rainfall start by focusing on one month' dataand then once your code is workingrun it for full year' data - exploregenerate few more visualizations that examine any other weather aspect you're interested in for any locations you're curious about mapping global data setsjson format in this sectionyou'll download location-based country data in the json format and work with it using the json module using pygal' beginnerfriendly mapping tool for country-based datayou'll create visualizations of this data that explore global patterns concerning the world' population distribution over different countries downloading world population data copy the file population_data jsonwhich contains population data from through for most of the world' countriesto the folder where you're storing this programs this data comes from one of the many data sets that the open knowledge foundation (makes freely available |
379 | let' look at population_data json to see how we might begin to process the data in the filepopulation_ data json "country name""arab world""country code""arb""year"" ""value"" }"country name""arab world""country code""arb""year"" ""value"" }--snip-the file is basically one long python list each item is dictionary with four keysa country namea country codea yearand value representing the population we want to examine each country' name and population only in so start by writing program to print just that informationworld_ population py import json load the data into list filename 'population_data jsonwith open(filenameas fu pop_data json load(fprint the population for each country for pop_dict in pop_dataw if pop_dict['year'=' ' country_name pop_dict['country name'population pop_dict['value'print(country_name "populationwe first import the json module to be able to load the data properly from the fileand then we store the data in pop_data at the json load(function converts the data into format python can work within this casea list at we loop through each item in pop_data each item is dictionary with four key-value pairsand we store each dictionary in pop_dict at we look for in the 'yearkey of each dictionary (because the values in population_data json are all in quoteswe do string comparison if the year is we store the value associated with 'country namein country_name and the value associated with 'valuein population at we then print the name of each country and its population downloading data |
380 | arab world caribbean small states east asia pacific (all income levels) --snip-zimbabwe not all of the data we captured includes exact country namesbut this is good start now we need to convert the data into format pygal can work with converting strings into numerical values every key and value in population_data json is stored as string to work with the population datawe need to convert the population strings to numerical values we do this using the int(functionworld_ population py --snip-for pop_dict in pop_dataif pop_dict['year'=' 'country_name pop_dict['country name' population int(pop_dict['value'] print(country_name "str(population)now we've stored each population value in numerical format at when we print the population valuewe need to convert it to string at howeverthis change results in an error for some valuesas shown herearab world caribbean small states east asia pacific (all income levels) --snip-traceback (most recent call last)file "print_populations py"line in population int(pop_dict['value'] valueerrorinvalid literal for int(with base ' it' often the case that raw data isn' formatted consistentlyso we come across errors lot here the error occurs because python can' directly turn string that contains decimal' 'into an integer (this decimal value is probably the result of interpolation for years when specific population count was not made we address this error by converting the string to float and then converting that float to an integerworld_ population py --snip-for pop_dict in pop_dataif pop_dict['year'=' 'country pop_dict['country name'population int(float(pop_dict['value'])print(country "str(population) |
381 | can print full set of population values for the year with no errorsarab world caribbean small states east asia pacific (all income levels) --snip-zimbabwe each string was successfully converted to float and then to an integer now that these population values are stored in numerical formatwe can use them to make world population map obtaining two-digit country codes before we can focus on mappingwe need to address one last aspect of the data the mapping tool in pygal expects data in particular formatcountries need to be provided as country codes and populations as values several standardized sets of country codes are frequently used when working with geopolitical datathe codes included in population_data json are three-letter codesbut pygal uses two-letter codes we need way to find the two-digit code from the country name pygal' country codes are stored in module called nshort for internationalization the dictionary countries contains the two-letter country codes as keys and the country names as values to see these codesimport the dictionary from the module and print its keys and valuescountries py from pygal import countries for country_code in sorted(countries keys())print(country_codecountries[country_code]in the for loop we tell python to sort the keys in alphabetical order then we print each country code and the country it' associated withad andorra ae united arab emirates af afghanistan --snip-zw zimbabwe to extract the country code datawe write function that searches through countries and returns the country code we'll write this in separate module called country_codes so we can later import it into visualization programcountry_ codes py from pygal import countries def get_country_code(country_name)"""return the pygal -digit country code for the given country ""downloading data |
382 | if name =country_namereturn code if the country wasn' foundreturn none return none print(get_country_code('andorra')print(get_country_code('united arab emirates')print(get_country_code('afghanistan')we pass get_country_code(the name of the country and store it in the parameter country_name we then loop through the code-name pairs in countries if the name of the country is foundthe country code is returned we add line after the loop to return none if the country name was not found finallywe pass three country names to check that the function works as expectedthe program outputs three two-letter country codesad ae af before using this functionremove the print statements from country_codes py next we import get_country_code(into world_population pyworld_ population py import json from country_codes import get_country_code --snip-print the population for each country for pop_dict in pop_dataif pop_dict['year'=' 'country_name pop_dict['country name'population int(float(pop_dict['value']) code get_country_code(country_nameif codev print(code ""str(population) elseprint('error country_nameafter extracting the country name and populationwe store the country code in code or none if no code is available if code is returnedthe code and country' population are printed if the code is not availablewe display an error message with the name of the country we can' find code for run this programand you'll see some country codes with their populations and some error lineserror arab world error caribbean small states error east asia pacific (all income levels |
383 | al dz --snip-error yemenrep zm zw the errors come from two sources firstnot all the classifications in the data set are by countrysome population statistics are for regions (arab worldand economic groups (all income levelssecondsome of the statistics use different system for full names of countries (yemenrep instead of yemenfor nowwe'll omit country data that cause errors and see what our map looks like for the data that we recovered successfully building world map with the country codes we haveit' quick and simple to make world map pygal includes worldmap chart type to help map global data sets as an example of how to use worldmapwe'll create simple map that highlights north americacentral americaand south americaamericas py import pygal wm pygal worldmap(wm title 'northcentraland south americav wm add('north america'['ca''mx''us']wm add('central america'['bz''cr''gt''hn''ni''pa''sv']wm add('south america'['ar''bo''br''cl''co''ec''gf''gy''pe''py''sr''uy''ve'] wm render_to_file('americas svg'at we make an instance of the worldmap class and set the map' title attribute at we use the add(methodwhich takes in label and list of country codes for the countries we want to focus on each call to add(sets up new color for the set of countries and adds that color to key on the left of the graph with the label specified here we want the entire region of north america represented in one colorso we place 'ca''mx'and 'usin the list we pass to the first add(call to highlight canadamexicoand the united states together we then do the same for the countries in central america and south america the method render_to_file(at creates an svg file containing the chartwhich you can open in your browser the output is map highlighting northcentraland south america in different colorsas shown in figure - downloading data |
384 | we now know how to make map with colored areasa keyand neat labels let' add data to our map to show information about country plotting numerical data on world map to practice plotting numerical data on mapcreate map showing the populations of the three countries in north americana_ populations py import pygal wm pygal worldmap(wm title 'populations of countries in north americau wm add('north america'{'ca' 'us' 'mx' }wm render_to_file('na_populations svg'first create worldmap instance and set title then use the add(methodbut this time pass dictionary as the second argument instead of list the dictionary has pygal two-letter country codes as its keys and population numbers as its values pygal automatically uses these numbers to shade the countries from light (least populatedto dark (most populatedfigure - shows the resulting map |
385 | this map is interactiveif you hover over each countryyou'll see its population let' add more data to our map plotting complete population map to plot population numbers for the rest of the countrieswe have to convert the country data we processed earlier into the dictionary format pygal expectswhich is two-letter country codes as keys and population numbers as values add the following code to world_population pyworld_ population py import json import pygal from country_codes import get_country_code load the data into list --snip-build dictionary of population data cc_populations {for pop_dict in pop_dataif pop_dict['year'=' 'country pop_dict['country name'population int(float(pop_dict['value'])code get_country_code(countrydownloading data |
386 | if codecc_populations[codepopulation wm pygal worldmap(wm title 'world population in by countryx wm add(' 'cc_populationswm render_to_file('world_population svg'we first import pygal at we create an empty dictionary to store country codes and populations in the format pygal expects at we build the cc_populations dictionary using the country code as key and the population as the value whenever code is returned we also remove all the print statements we make worldmap instance and set its title attribute when we call add()we pass it the dictionary of country codes and population values figure - shows the map that' generated figure - the world' population in we don' have data for few countrieswhich are colored in blackbut most countries are colored according to their population size you'll deal with the missing data later in this but first we'll alter the shading to more accurately reflect the population of the countries currentlyour map shows many lightly shaded countries and two darkly shaded countries the contrast between most of the countries isn' enough to indicate how populated they are relative to each other we'll fix this by grouping countries into population levels and shading each group |
387 | because china and india are more heavily populated than other countriesthe map shows little contrast china and india are each home to over billion peoplewhereas the next most populous country is the united states with approximately million people instead of plotting all countries as one grouplet' separate the countries into three population levelsless than millionbetween million and billionand more than billionworld_ population py --snip-build dictionary of population data cc_populations {for pop_dict in pop_dataif pop_dict['year'=' '--snip-if codecc_populations[codepopulation group the countries into population levels cc_pops_ cc_pops_ cc_pops_ {}{}{ for ccpop in cc_populations items()if pop cc_pops_ [ccpop elif pop cc_pops_ [ccpop elsecc_pops_ [ccpop see how many countries are in each level print(len(cc_pops_ )len(cc_pops_ )len(cc_pops_ )wm pygal worldmap(wm title 'world population in by countryx wm add(' - 'cc_pops_ wm add(' - bn'cc_pops_ wm add('> bn'cc_pops_ wm render_to_file('world_population svg'to group the countrieswe create an empty dictionary for each category we then loop through cc_populations to check the population of each country the ifelifelse block adds an entry to the appropriate dictionary (cc_pops_ cc_pops_ or cc_pops_ for each country codepopulation pair at we print the length of each of these dictionaries to find out the sizes of the groups when we plot the data xwe make sure to add all three groups to the worldmap when you run this programyou'll first see the size of each group downloading data |
388 | million people countries with between million and billion peopleand two outlier countries with over billion this seems like an even enough split for an informative map figure - shows the resulting map figure - the world' population shown in three different groups now three different colors help us see the distinctions between population levels within each of the three levelscountries are shaded from light to dark for smallest to largest population styling world maps in pygal although the population groups in our map are effectivethe default color settings are pretty uglyfor examplehere pygal has chosen garish pink and green motif we'll use pygal' styling directives to rectify the colors let' direct pygal to use one base color againbut this time we'll choose the color and apply more distinct shading for the three population groupsworld_ population py import json import pygal from pygal style import rotatestyle --snip-group the countries into population levels cc_pops_ cc_pops_ cc_pops_ {}{}{ |
389 | if pop --snip- wm_style rotatestyle('# ' wm pygal worldmap(style=wm_stylewm title 'world population in by country--snip-pygal styles are stored in the style module from which we import the style rotatestyle this class takes one argumentan rgb color in hex format pygal then chooses colors for each of the groups based on the color provided the hex format is string with hash mark (#followed by six charactersthe first two represent the red component of the colorthe next two represent the green componentand the last two represent the blue component the component values can range from (none of that colorto ff (maximum amount of that colorif you search online for hex color chooseryou should find tool that will let you experiment with colors and give you the rgb values the color used here (# mixes bit of red ( ) little more green ( )and even more blue ( to give rotatestyle light blue base color to work from rotatestyle returns style objectwhich we store in wm_style to use this style objectpass it as keyword argument when you make an instance of worldmap figure - shows the updated chart figure - the three population groups in unified color theme downloading data |
390 | are easy to distinguish lightening the color theme pygal tends to use dark themes by default for the purposes of printingi've lightened the style of my charts using lightcolorizedstyle this class changes the overall theme of the chartincluding the background and labels as well as the individual country colors to use itfirst import the stylefrom pygal style import lightcolorizedstyle you can then use lightcolorizedstyle on its ownas suchwm_style lightcolorizedstyle but this class gives you no direct control over the color usedso pygal will choose default base color to set coloruse lightcolorizedstyle as base for rotatestyle import both lightcolorizedstyle and rotatestylefrom pygal style import lightcolorizedstylerotatestyle then create style using rotatestylebut pass it an additional base_style argumentwm_style rotatestyle('# 'base_style=lightcolorizedstylethis gives you light overall theme but bases the country colors on the color you pass as an argument with this style you'll see that your charts match the screenshots here bit more closely while you're experimenting to find styling directives that work well for different visualizationsit can help to use aliases in your import statementsfrom pygal style import lightcolorizedstyle as lcsrotatestyle as rs this will result in shorter style definitionswm_style rs('# 'base_style=lcsusing just this small set of styling directives gives you significant control over the appearance of charts and maps in pygal |
391 | - all countrieson the population maps we made in this sectionour program couldn' automatically find two-letter codes for about countries work out which countries are missing codesand look through the countries dictionary for the codes add an ifelif block to get_country_code(so it returns the correct country code values for these specific countriesif country_name ='yemenrep return 'yeelif --snip-place this code after the countries loop but before the return none statement when you're finishedyou should see more complete map - gross domestic productthe open knowledge foundation maintains data set containing the gross domestic product (gdpfor each country in the worldwhich you can find at the json version of this data setand plot the gdp of each country in the world for the most recent year in the data set - choose your own datathe world bank maintains many data sets that are broken down for information on each country worldwide go to data worldbank org/indicatorand find data set that looks interesting click the data setclick the download data linkand choose csv you'll receive three csv filestwo of which are labeled metadatause the third csv file write program that generates dictionary with pygal' two-letter country codes as its keys and your chosen data from the file as its values plot the data on worldmap and style the map as you like - testing the country_codes modulewhen we wrote the country_codes modulewe used print statements to check whether the get_country_code(function worked write proper test for this function using what you learned in summary in this you learned to work with online data sets you learned how to process csv and json filesand extract the data you want to focus on using historical weather datayou learned more about working with matplotlibincluding how to use the datetime module and how to plot multiple data series on one chart you learned to plot country data on world map in pygal and to style pygal maps and charts downloading data |
392 | process almost any data you want to analyze most online data sets can be downloaded in either or both of these formats from working with these formatsyou'll be able to learn other data formats as well in the next you'll write programs that automatically gather their own data from online sourcesand then you'll create visualizations of that data these are fun skills to have if you want to program as hobby and critical skills if you're interested in programming professionally |
393 | working with apis in this you'll learn how to write self-contained program to generate visualization based on data that it retrieves your program will use web application programming interface (apito automatically request specific information from website rather than entire pages it will then use that information to generate visualization because programs written like this will always use current data to generate visualizationeven when that data might be rapidly changingit will always be up to date |
394 | web api is part of website designed to interact with programs that use very specific urls to request certain information this kind of request is called an api call the requested data will be returned in an easily processed formatsuch as json or csv most apps that rely on external data sourcessuch as apps that integrate with social media sitesrely on api calls git and github we'll base our visualization on information from githuba site that allows programmers to collaborate on projects we'll use github' api to request information about python projects on the site and then generate an interactive visualization of the relative popularity of these projects in pygal github (projects git helps people manage their individual work on projectso changes made by one person won' interfere with changes other people are making when you're implementing new feature in projectgit tracks the changes you make to each file when your new code worksyou commit the changes you've madeand git records the new state of your project if you make mistake and want to revert your changesyou can easily return to any previously working state (to learn more about version control using gitsee appendix projects on github are stored in repositorieswhich contain everything associated with the projectits codeinformation on its collaboratorsany issues or bug reportsand so on when users on github like projectthey can "starit to show their support and keep track of projects they might want to use in this we'll write program to automatically download information about the most-starred python projects on githuband then we'll create an informative visualization of these projects requesting data using an api call github' api lets you request wide range of information through api calls to see what an api call looks likeenter the following into your browser' address bar and press enterthis call returns the number of python projects currently hosted on githubas well as information about the most popular python repositories let' examine the call the first partrequest to the part of github' website that responds to api calls the next partsearch/repositoriestells the api to conduct search through all repositories on github the question mark after repositories signals that we're about to pass an argument the stands for queryand the equal sign lets us begin |
395 | information only on repositories that have python as the primary language the final part&sort=starssorts the projects by the number of stars they've been given the following snippet shows the first few lines of the response you can see from the response that this url is not intended to be entered by humans "total_count" "incomplete_results"false"items""id" "name""httpie""full_name""jkbrzt/httpie"--snip-as you can see in the second line of outputgithub found total of , python projects as of this writing because the value for "incomplete_resultsis falsewe know that the request was successful (it' not incompleteif github had been unable to fully process the api requestit would have returned true here the "itemsreturned are displayed in the list that followswhich contains details about the most popular python projects on github installing requests the requests package allows python program to easily request information from website and examine the response that' returned to install requestsissue command like the followingpip install --user requests if you haven' used pip yetsee "installing python packages with pipon page (you may need to use slightly different version of this commanddepending on your system' setup processing an api response now we'll begin to write program to issue an api call and process the results by identifying the most starred python projects on githubpython_ import requests repos py make an api call and store the response url ' requests get(urlx print("status code:" status_codeworking with apis |
396 | response_dict json(process results print(response_dict keys()at we import the requests module at we store the url of the api calland then we use requests to make the call we call get(and pass it the urland we store the response object in the variable the response object has an attribute called status_codewhich tells us whether the request was successful ( status code of indicates successful response at we print the value of status_code to make sure the call went through successfully the api returns the information in json formatso we use the json(method to convert the information to python dictionary we store the resulting dictionary in response_dict finallywe print the keys from response_dict and see thisstatus code dict_keys(['items''total_count''incomplete_results']because the status code is we know that the request was successful the response dictionary contains only three keys'items''total_count'and 'incomplete_resultsnote simple calls like this should return complete set of resultsso it' pretty safe to ignore the value associated with 'incomplete_resultsbut when you're making more complex api callsyour program should check this value working with the response dictionary now that we have the information from the api call stored as dictionarywe can work with the data stored there let' generate some output that summarizes the information this is good way to make sure we received the information we expected and to start examining the information we're interested inpython_ repos py import requests make an api call and store the response url ' requests get(urlprint("status code:" status_codestore api response in variable response_dict json( print("total repositories:"response_dict['total_count']explore information about the repositories repo_dicts response_dict['items'print("repositories returned:"len(repo_dicts) |
397 | repo_dict repo_dicts[ print("\nkeys:"len(repo_dict) for key in sorted(repo_dict keys())print(keyat we print the value associated with 'total_count'which represents the total number of python repositories on github the value associated with 'itemsis list containing number of dictionarieseach of which contains data about an individual python repository at we store this list of dictionaries in repo_dicts we then print the length of repo_dicts to see how many repositories we have information for to take closer look at the information returned about each repositorywe pull out the first item from repo_dicts and store it in repo_dict we then print the number of keys in the dictionary to see how much information we have at we print all of the dictionary' keys to see what kind of information is included the results start to give us clearer picture of the actual datastatus code total repositories repositories returned keys archive_url assignees_url blobs_url --snip-url watchers watchers_count github' api returns lot of information about each repositorythere are keys in repo_dict when you look through these keysyou'll get sense of the kind of information you can extract about project (the only way to know what information is available through an api is to read the documentation or to examine the information through codeas we're doing here let' pull out the values for some of the keys in repo_dictpython_ repos py --snip-explore information about the repositories repo_dicts response_dict['items'print("repositories returned:"len(repo_dicts)examine the first repository repo_dict repo_dicts[ print("\nselected information about first repository:" print('name:'repo_dict['name'] print('owner:'repo_dict['owner']['login']working with apis |
398 | print('repository:'repo_dict['html_url'] print('created:'repo_dict['created_at']print('updated:'repo_dict['updated_at']print('description:'repo_dict['description']here we print out the values for number of keys from the first repository' dictionary at we print the name of the project an entire dictionary represents the project' ownerso at we use the key owner to access the dictionary representing the owner and then use the key login to get the owner' login name at we print how many stars the project has earned and the url for the project' github repository we then show when it was created and when it was last updated finallywe print the repository' descriptionand the output should look something like thisstatus code total repositories repositories returned selected information about first repositorynamehttpie ownerjkbrzt stars repositorycreatedt : : updatedt : : descriptioncli http clientuser-friendly curl replacement featuring intuitive uijson supportsyntax highlightingwget-like downloadsextensionsetc we can see that the most-starred python project on github as of this writing is httpieits owner is user jkbrztand it has been starred by more than , github users we can see the url for the project' repositoryits creation date of february and that it was updated recently finallythe description tells us that httpie helps make http calls from terminal (cli is short for command line interfacesummarizing the top repositories when we make visualization for this datawe'll want to include more than one repository let' write loop to print selected information about each of the repositories returned by the api call so we can include them all in the visualizationpython_ repos py --snip-explore information about the repositories repo_dicts response_dict['items'print("repositories returned:"len(repo_dicts) |
399 | for repo_dict in repo_dictsprint('\nname:'repo_dict['name']print('owner:'repo_dict['owner']['login']print('stars:'repo_dict['stargazers_count']print('repository:'repo_dict['html_url']print('description:'repo_dict['description']we print an introductory message at at we loop through all the dictionaries in repo_dicts inside the loop we print the name of each projectits ownerhow many stars it hasits url on githuband the project' descriptionstatus code total repositories repositories returned selected information about each repositorynamehttpie ownerjkbrzt stars repositorydescriptioncli http clientuser-friendly curl replacement featuring intuitive uijson supportsyntax highlightingwget-like downloadsextensionsetc namedjango ownerdjango stars repositorydescriptionthe web framework for perfectionists with deadlines --snip-namepowerline ownerpowerline stars repositorydescriptionpowerline is statusline plugin for vimand provides statuslines and prompts for several other applicationsincluding zshbashtmuxipythonawesome and qtile some interesting projects appear in these resultsand it might be worth taking look at few but don' spend too long on itbecause we're about to create visualization that will make it much easier to read through the results monitoring api rate limits most apis are rate-limitedwhich means there' limit to how many requests you can make in certain amount of time to see if you're working with apis |